Start sequence on Monday, end on Friday
Given a random start and end dates, how can I create a new sequence (or modify this one) to start on the first Monday and finish on the last Friday?
MyDays <- seq(StartDate , EndDate , by = "day")
SequenceDay <- days [!is.weekend(MyDays)]
开发者_如何学C
Thanks!
Similar to Tony Breyal's answer. Be aware these only work if your system uses English language spellings for the days of the week.
StartDate <- as.Date("2010-01-01")
EndDate <- as.Date("2010-12-31")
myDays <- seq(StartDate , EndDate, by = "day")
excludeDays <- c("Saturday", "Sunday")
myWeekDays <- subset(myDays, !weekdays(myDays) %in% excludeDays)
firstMonday <- which(weekdays(head(myWeekDays, 5)) == "Monday")
lastFriday <- length(myWeekDays) - 5 +
which(weekdays(tail(myWeekDays, 5)) == "Friday")
myCompleteWeeks <- myWeekDays[firstMonday:lastFriday]
POSIXlt gives you a language-independent way. match()
and rev()
make a bit easier comparison. The chron
package contains the function is.weekend()
. Using the vector myDays of Winchester :
myDays <- as.POSIXlt(myDays)
wdays <- myDays$wday
n <- length(myDays)+1
myDays <- myDays[match(1,wdays):(n-match(5,rev(wdays)))]
To exclude the weekends, you can use the chron library
library(chron)
myDays[!is.weekend(myDays)]
This works with POSIXt, Date and chron objects, so you can use it independently of the other code. With POSIXlt you can just use %in% again as well :
myDays[! myDays$wday %in% c(0,6)]
Assuming I understood correctly ('tis currently the end of the working day and I'm at the pub), then how about this:
# set start and end dates
n <- 31
d.start <- Sys.Date()
d.end <- d.start + n
# workhorse code
my.seq = seq(d.start, d.end, "days")
x1 <- weekdays(my.seq)
first.Mon <- which(x1=="Monday")[1]
last.friday <- which(x1=="Friday")[length(which(x1=="Friday"))]
x <- my.seq[first.Mon:last.Fri]
ind.sats <- which(weekdays(x) == "Saturday")
ind.suns <- which(weekdays(x) == "Sunday")
x <- x[-c(ind.sats, ind.suns)]
Which should give you:
> x
[1] "2011-03-07" "2011-03-08" "2011-03-09" "2011-03-10" "2011-03-11"
[6] "2011-03-14" "2011-03-15" "2011-03-16" "2011-03-17" "2011-03-18"
[11] "2011-03-21" "2011-03-22" "2011-03-23" "2011-03-24" "2011-03-25"
[16] "2011-03-28" "2011-03-29" "2011-03-30" "2011-03-31" "2011-04-01"
or
> weekdays(x)
[1] "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Monday"
[7] "Tuesday" "Wednesday" "Thursday" "Friday" "Monday" "Tuesday"
[13] "Wednesday" "Thursday" "Friday" "Monday" "Tuesday" "Wednesday"
[19] "Thursday" "Friday"
Depending on what it is you wanted. That's the basic idea anyway, you'll probably need to add some error checking.
精彩评论