我正在使用以下代码:
dates<-seq(as.Date("1991/1/4"),as.Date("2010/3/1"),"days")
但是,我想只有工作日,怎么办?(假设 1991/1/4 是星期一,我想排除:1991/6/4 和 1991/7/4。每周都是这样。)
感谢您的帮助。
这对你有用吗?(注意,它需要安装 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)
您输入的日期不正确。为了使用 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
我在查找工作日功能时遇到了这个问题,并且由于 OP 要求“工作日”而不是“工作日”,并且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