0

I'm trying to count the number of Saturdays and then Sundays in a specific month within R.

So for example if you entered the month for example Feb-2014 into the function it would return 4 for Saturday and 4 for Sunday. But if you input Jan-2015 it would return 5 for Saturday and 4 for Sunday.

Any ideas?

rossi_182
  • 55
  • 1
  • 7

1 Answers1

1

You can use lubridate for this. Here's a simple example. You'll have to pass it actual dates (not just months, though):

library("lubridate")
weekend_days <- function(x) {
  x <- as.Date(x)
  d <- days_in_month(x)
  d <- x + (0:(d-1))
  sum(wday(d) %in% c(1,7))
}

Some examples (for January and February 2012):

weekend_days("2012-01-01")
# [1] 9
weekend_days("2012-02-01")
# [1] 8
Thomas
  • 43,637
  • 12
  • 109
  • 140
  • Thanks @Thomas, I made a gist based on this function to count the number of weekdays before/after a specified input date. https://gist.github.com/plnnr/0a2c0206f7521598ba1ead9daf02acfd – oatmilkyway Feb 03 '22 at 19:29