r - R向量计数每个日期范围内的日期数
问题描述
我正在寻找实现创建新变量的最佳方法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
解决方案
如果对 Rcpp 的依赖不是问题,我喜欢它用于此类任务,因为它易于维护。
library(Rcpp)
cppFunction('
NumericVector count365(const NumericVector x) {
// assumes that x is sorted
size_t n = x.size();
//initialize vector of zeros for counts
NumericVector N = NumericVector(n);
double lim;
// start loop from second element of x
for (size_t i = 1; i < n; ++i) {
lim = x[i] - 365;
//loop backwards from preceding element
for (size_t j = i-1; j >= 0; --j) {
//check if within 365 day range
if (x[j] >= lim) {
N[i]++;
} else {
break;
}
}
}
return N;
}
')
df$numWithin365 <- count365(df$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
推荐阅读
- angular - HighMaps 从列表中选择地图 - Highcharts.geojson 和 Highcharts.mapDataIndex 问题
- amazon-web-services - 当我的密钥有空格时出现 AWS S3 CLI 错误
- angular - 从 nginx 服务器而不是 environment.ts 文件访问环境变量
- excel - 应用程序用户名错误的 Excel/VBA 问题
- macos - 如何在 macOS 上捕获 intel-pt 数据包
- javascript - Knp/Snappy PDF 生成器空白页
- python - 如何在 matplotlib 图上叠加 seaborn 热图
- angular - 如何在 Html5 视频标签中设置质量选项
- css - 如何使 v-tabs-items 和 v-tab-item 填充高度
- javascript - 为什么这里的结果是-40?