I like to count the number of Sundays, Mondays, Tuesdays, ...,Saturdays in year 2001. Taking the following dates { 1 Jan, 5 April, 13 April, 25 Dec and 26 Dec} as public holidays and consider them as Sundays. How can I do it in R? - Thanks
            Asked
            
        
        
            Active
            
        
            Viewed 864 times
        
    1
            
            
        - 
                    3You will find that you get better answers if you take the time to make your question reproducible. Please follow the guidelines (http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), paying special attention to the part about `dput()`. Thanks! – Ari B. Friedman Jul 25 '12 at 15:01
2 Answers
5
            Here is the Lithuanian version:
dates <- as.Date("2001-01-01") + 0:364
wd <- weekdays(dates)
idx <- which(dates %in% as.Date(c("2001-01-01", "2001-04-05", 
             "2001-04-13", "2001-12-25", "2001-12-26")))
wd[idx] <- "sekmadienis"
table(wd)
wd
   antradienis ketvirtadienis   penktadienis    pirmadienis    sekmadienis    šeštadienis   trečiadienis 
            51             51             51             52             57             52             51 
 
    
    
        Julius Vainora
        
- 47,421
- 9
- 90
- 102
3
            
            
        Try the following:
# get all the dates you need
dates <- seq(from=as.Date("2001-01-01"), to=as.Date("2001-12-31"), by="day")
# makes sure the dates are in POSIXlt format
dates <- strptime(dates, "%Y-%m-%d")
# get rid of the public holidays
pub <- strptime(c(as.Date("2001-01-01"), 
                 as.Date("2001-04-05"), 
                 as.Date("2001-04-13"), 
                 as.Date("2001-12-25"), 
                 as.Date("2001-12-26")), "%Y-%m-%d")
dates <- dates[which(!dates%in%pub)]
# To see the day of the week
weekdays <- dates$wday
# Now, count the number of Mondays for example:
length(which(weekdays == 1))
For details, see the documentation for DateTimeClasses. Remember to add 5 to your count of Sundays.
 
    
    
        Edward
        
- 5,367
- 1
- 20
- 17
- 
                    From the solution by Julius, there is definitely a more graceful way to handle the public holidays. Take out the line `dates <- dates[which(!dates%in%pub)]` and insert `weekdays[dates%in%pub] <- 0` after creating weekdays. Now you won't need to account for them when counting Sundays. Thanks Julius! – Edward Jul 25 '12 at 18:07
