如何修改data.table代码以按指定列条件统计过去一年的匹配行数
嘿,我来帮你搞定这个data.table的统计问题~
你的需求很明确:对每一行数据,统计相同id、时间在当前行日期往前推365天到当前日期之间,并且type等于1的记录数量。之前尝试的.N(type = 1)写法不对,我们可以通过两种方式修改代码来实现需求:
方法一:先过滤再统计
我们可以在连接的右表中先筛选出type == 1的记录,这样统计的就是符合条件的行数:
library(data.table) # 先构造你的示例数据集 df <- data.table( id = c("ny", "ny", "ny", "ny", "ch", "ch", "ch"), type = c(0, 0, 1, 1, 0, 1, 0), date = as.Date(c("2021-09-27", "2021-09-09", "2021-08-01", "2021-07-07", "2020-04-01", "2020-03-01", "2020-02-01")) ) # 计算每行的时间边界(当前日期减365天) df[, boundary := date - 365] # 修改后的统计代码:只统计type=1的记录 df[, counts := df[type == 1, .N, on = .(id, date < date, date > boundary), by = .EACHI]$N] # 把没有符合条件的NA替换为0,匹配你的预期输出 df[, counts := ifelse(is.na(counts), 0, counts)]
方法二:通过求和统计
另一种思路是在连接后对每组的type == 1条件求和(满足条件加1,不满足加0),效果完全一致:
df[, counts := df[df, sum(type == 1), on = .(id, date < date, date > boundary), by = .EACHI]$V1] df[, counts := ifelse(is.na(counts), 0, counts)]
验证结果
运行任意一种方法后,你都会得到和预期完全匹配的结果:
| id | type | date | boundary | counts |
|---|---|---|---|---|
| ny | 0 | 2021-09-27 | 2020-09-27 | 2 |
| ny | 0 | 2021-09-09 | 2020-09-09 | 2 |
| ny | 1 | 2021-08-01 | 2020-08-01 | 1 |
| ny | 1 | 2021-07-07 | 2020-07-07 | 0 |
| ch | 0 | 2020-04-01 | 2019-04-01 | 1 |
| ch | 1 | 2020-03-01 | 2019-03-01 | 0 |
| ch | 0 | 2020-02-01 | 2019-02-01 | 0 |
补充说明
- 为什么原来的写法不对?
.N是用来统计分组行数的参数,不能直接加条件筛选,要么先过滤数据集,要么用sum()来计数符合条件的行。 - 替换
NA为0是因为当没有符合条件的记录时,统计结果会返回NA,而你的预期是显示0,这一步是必要的。
内容的提问来源于stack exchange,提问作者fifigoblin
相关产品推荐
相关产品推荐

