我正在寻找实现创建新变量的最佳方法numWithin365,定义如下:
给定一列日期,dates计算前 365 天内该列中其他日期的数量。这个问题可以推广到日期向量之外。
这是一种实现;我正在寻找任何可以帮助它更好地扩展的建议。
library(dplyr)
# set seed for reproducibility
set.seed(42)
# function to calculate number of dates in prior year
within365 <- function(col){
sapply(col, function(x){
sum(x-365 < col & col <= x-1)
}
)
}
# fake data sorted chronologically
df <- data.frame(dates = sample(seq(as.Date('2015/01/01'), as.Date('2020/12/31'),
by="day"), 10)) %>% arrange(dates)
# applying the function
df %>% mutate(numWithin365 = within365(dates))
Run Code Online (Sandbox Code Playgroud)
dates numWithin365
1 2015-12-22 0
2 2016-09-25 1
3 2018-01-02 0
4 2018-02-25 1 …Run Code Online (Sandbox Code Playgroud)