例如。 df有两列名为c(" Today"," Expiration")。我希望得到一个新的领域" Workdays"。但是当我写这样的时候,我失败了:
Today <- seq.Date(as.Date("2015-10-01"), as.Date("2015-10-11"), by = "days")
Expiration <- seq.Date(as.Date("2015-10-20"), as.Date("2015-10-30"), by = "day")
df <- data.frame(Today, Expiration)
df <- transform(df, Workdays = sum(!weekdays(seq.Date(Today, Expiration, "days")) %in% c("Saturday", "Sunday")))
seq.Date(今天,过期,&#34;天和#34;)出现错误:&#39;来自&#39;必须长度为1
警告是&#34;今天&#34;应该是1的长度。
请帮帮我,谢谢!
也许计算直接效果更好
d <- with(df, Expiration - Today)
d <- as.numeric(d)
Workdays <- d - ((d - 1) %/% 7 ) * 2 - ifelse(d %% 7 == 0, 2, ifelse(d %% 7 == 6, 1, 0)
答案 0 :(得分:1)
我们可以使用data.table
。我们可以转换&#39; data.frame&#39;到&#39; data.table&#39; (setDT(df)
,按行序列(1:nrow(df)
)分组,我们得到逻辑条件的sum
并指定(:=
)作为新列(&#39;工作日&#39;。)
library(data.table)
setDT(df)[, Workdays:=sum(!weekdays(seq(Today, Expiration, by = 'day')) %in%
c('Saturday', 'Sunday')) , 1:nrow(df)]