给定一个随机的开始和结束日期,我如何创建一个新的序列(或修改这个序列)从第一个星期一开始到最后一个星期五结束?
MyDays <- seq(StartDate , EndDate , by = "day")
SequenceDay <- days [!is.weekend(MyDays)]
谢谢!
答案 0 :(得分:3)
与Tony Breyal的回答相似。请注意,只有当您的系统在一周中的某几天使用英语拼写时,这些才有效。
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]
答案 1 :(得分:3)
POSIXlt为您提供与语言无关的方式。 match()
和rev()
比较容易一些。 chron
包中包含函数is.weekend()
。使用温彻斯特的矢量myDays:
myDays <- as.POSIXlt(myDays)
wdays <- myDays$wday
n <- length(myDays)+1
myDays <- myDays[match(1,wdays):(n-match(5,rev(wdays)))]
要排除周末,您可以使用chron库
library(chron)
myDays[!is.weekend(myDays)]
这适用于POSIXt,Date和chron对象,因此您可以独立于其他代码使用它。使用POSIXlt,您也可以再次使用%in%:
myDays[! myDays$wday %in% c(0,6)]
答案 2 :(得分:2)
假设我理解正确('目前是工作日的结束而我在酒吧),那么这个怎么样:
# 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)]
哪个应该给你:
> 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"
或
> 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"
取决于你想要的是什么。无论如何,这是基本的想法,你可能需要添加一些错误检查。