![](/img/trans.png)
[英]Count the number of entries that fall within a range of dates in a separate dataframe in R
[英]R vector count number of dates within range of each date
我正在寻找实现创建新变量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))
dates numWithin365
1 2015-12-22 0
2 2016-09-25 1
3 2018-01-02 0
4 2018-02-25 1
5 2018-03-22 2
6 2018-06-05 3
7 2018-08-19 4
8 2019-06-13 1
9 2020-09-02 0
10 2020-09-27 1
我们可以创建一个新列,从dates
列中减去 365 天,然后使用fuzzy_left_join
根据日期范围加入。
library(fuzzyjoin)
library(dplyr)
df1 <- df %>% mutate(dates1 = dates - 365)
fuzzy_left_join(df1, df1, by = c('dates1' = 'dates', 'dates'),
match_fun = c(`<`, `>`)) %>%
group_by(dates = dates.x) %>%
summarise(numWithin365 = sum(!is.na(dates.y)))
# dates numWithin365
# * <date> <int>
# 1 2015-12-22 0
# 2 2016-09-25 1
# 3 2018-01-02 0
# 4 2018-02-25 1
# 5 2018-03-22 2
# 6 2018-06-05 3
# 7 2018-08-19 4
# 8 2019-06-13 1
# 9 2020-09-02 0
#10 2020-09-27 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.