我使用以下代码:
dates<-seq(as.Date("1991/1/4"),as.Date("2010/3/1"),"days")
但是,我想只有工作日,怎么办呢? (假设1991/1/4是星期一,我想排除:1991/6/4和1991/7/4。 每周一次。)
感谢您的帮助。
答案 0 :(得分:7)
您输入的日期不正确。为了使用1991/1/4星期一隐含的YYYY / DD / MM输入模式,你需要在as.Date中有一个格式字符串。
因此,假设您要排除周末的完整解决方案是:
X <- seq( as.Date("1991/1/4", format="%Y/%m/%d"), as.Date("2010/3/1", format="%Y/%m/%d"),"days")
weekdays.X <- X[ ! weekdays(X) %in% c("Saturday", "Sunday") ]
# negation easier since only two cases in exclusion
# probably do not want to print that vector to screen.
str(weekdays.X)
关于你的评论,我无法重现。我明白了:
> table(weekdays(weekdays.X) )
Friday Monday Thursday Tuesday Wednesday
1000 1000 999 999 999
答案 1 :(得分:5)
这对你有用吗? (注意,它需要安装timeDate包)
# install.packages('timeDate')
require(timeDate)
# A ’timeDate’ Sequence
tS <- timeSequence(as.Date("1991/1/4"), as.Date("2010/3/1"))
tS
# Subset weekdays
tW <- tS[isWeekday(tS)]; tW
dayOfWeek(tW)
答案 2 :(得分:4)
我在查找工作日功能时遇到了这个问题,并且由于OP要求&#34;工作日&#34;而不是&#34;工作日&#34;和timeDate
也有isBizday
功能,这个答案使用了它。
# A timeDate Sequence
date.sequence <- timeSequence(as.Date("1991-12-15"), as.Date("1992-01-15")); # a short example period with three London holidays
date.sequence;
# holidays in the period
years.included <- unique( as.integer( format( x=date.sequence, format="%Y" ) ) );
holidays <- holidayLONDON(years.included) # (locale was not specified by OP in question nor in profile, so this assumes for example: holidayLONDON; also supported by timeDate are: holidayNERC, holidayNYSE, holidayTSX & holidayZURICH)
# Subset business days
business.days <- date.sequence[isBizday(date.sequence, holidays)];
business.days