我使用以下代码:
dates<-seq(as.Date("1991/1/4"),as.Date("2010/3/1"),"days")
Run Code Online (Sandbox Code Playgroud)
但是,我想只有工作日,怎么办呢?(假设1991/1/4是星期一,我想排除:1991/6/4和1991/7/4.并且每周都有.)
谢谢您的帮助.
您输入的日期不正确.为了使用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)
Run Code Online (Sandbox Code Playgroud)
关于你的评论,我无法重现.我明白了:
> table(weekdays(weekdays.X) )
Friday Monday Thursday Tuesday Wednesday
1000 1000 999 999 999
Run Code Online (Sandbox Code Playgroud)
这对你有用吗?(注意,它需要安装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)
Run Code Online (Sandbox Code Playgroud)
我在查找工作日功能时遇到了这个问题,并且由于 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
Run Code Online (Sandbox Code Playgroud)