ali srn ali srn - 2 months ago 12
R Question

Weekends in a Month in R

I am trying to prepare an xreg serie for my Arima model and I will use number of weekends in a month for it. I can find results for a year but when it is longer than a year, it usually is, I couldn't find a way.
Here is what I do so far.

dates <- seq(from=as.Date("2001-01-01"), to=as.Date("2010-12-31"), by = "day")
wd <- weekdays(dates)
aylar <- months(dates[which(wd == "Sunday" | wd == "Satuday")])

table(aylar)


What I want is gathering all months' weekends not based on only months but also years. So that I can have the same length of serie with my original forecast serie.

J_F J_F
Answer

Here is my solution:

library(chron)
library(dplyr)
library(lubridate)

month <- months(dates[chron::is.weekend(dates)])
day <- dates[chron::is.weekend(dates)]

# create data.frame
df <- data.frame(date = day, month = month, year = chron::years(day))

df %>% group_by(year, month) %>% summarize(weekends = floor(n()/2))

#   year    month weekends
#   <dbl>   <fctr>    <dbl>
#1   2001    April        4
#2   2001   August        4
#3   2001 Dezember        5
#4   2001  Februar        4
#5   2001   Januar        4
#6   2001     Juli        4
#7   2001     Juni        4
#8   2001      Mai        4
#9   2001     März        4
#10  2001 November        4
## ... with 110 more rows

I hope this is a starting point for your work.