Tony
Tony

Reputation: 2929

Counting the number of Sundays, Mondays,...,Saturdays

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

Upvotes: 1

Views: 875

Answers (2)

Edward
Edward

Reputation: 5537

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.

Upvotes: 3

Julius Vainora
Julius Vainora

Reputation: 48211

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 

Upvotes: 5

Related Questions