根据之前的文章,我可以用下面的方法添加一个列来统计过去一年的发生次数:
df[, boundary := date - 365]
df[, counts := df[df, .N, on = .(id, date < date, date > boundary), by = .EACHI]$N]
这对我来说很好。但是,我想通过只计算另一列具有特定值的出现次数来实现这一点。例如,给定如下的数据集
id type date
ny 0 2021-09-27
ny 0 2021-09-09
ny 1 2021-08-01
ny 1 2021-07-07
ch 0 2020-04-01
ch 1 2020-03-01
ch 0 2020-02-01
我只想计算type = 1
。我如何修改上面的函数来做到这一点?我试过这样做,但它不起作用:
df[, counts := df[df, .N(type = 1), on = .(id, date < date, date > boundary), by = .EACHI]$N]
编辑:上述数据集的预期输出将是:
id type date counts
ny 0 2021-09-27 2
ny 0 2021-09-09 2
ny 1 2021-08-01 1
ny 1 2021-07-07 0
ch 0 2020-04-01 1
ch 1 2020-03-01 0
ch 0 2020-02-01 0
可以用sum(type == 1)
代替.N
。
setDT(df)
df[, boundary := date - 365]
df[, counts := df[df, sum(type == 1),
on = .(id, date < date, date > boundary), by = .EACHI]$V1]
df[is.na(counts), counts := 0]
df
# id type date boundary counts
#1: ny 0 2021-09-27 2020-09-27 2
#2: ny 0 2021-09-09 2020-09-09 2
#3: ny 1 2021-08-01 2020-08-01 1
#4: ny 1 2021-07-07 2020-07-07 0
#5: ch 0 2020-04-01 2019-04-02 1
#6: ch 1 2020-03-01 2019-03-02 0
#7: ch 0 2020-02-01 2019-02-01 0