根据日期在 R 数据中按组对行求和 shares/number。table/frame

Sum shares/number of rows according to date by groups in R data.table/frame

我想计算 B 组(country)在过去一年中 A 组(industry)的唯一值的出现次数(分别为行数)的平方和。

计算示例第 5 行2x A + 1x B + 1x C = 2^2+1^2+^+1^2 = 6(不包括第 1 行的 A,因为它早于一年,也不包括第 6 行的 A因为它在另一个国家)。

我设法按行计算数字,但未能将其移动到聚合日期级别:

dt[, count_by_industry:= sapply(date, function(x) length(industry[between(date, x - lubridate::years(1), x)])), 
    by = c("country", "industry")]

该解决方案理想地扩展到具有约 200 万行和大约 1 万个日期和组元素的真实数据(因此 data.table 标签)。


示例数据

ID    <- c("1","2","3","4","5","6")
Date <- c("2016-01-02","2017-01-01", "2017-01-03", "2017-01-03", "2017-01-04","2017-01-03")
Industry <- c("A","A","B","C","A","A")
Country <- c("UK","UK","UK","UK","UK","US")
Desired <- c(1,4,3,3,6,1)

library(data.table)
dt <- data.frame(id=ID, date=Date, industry=Industry, country=Country, desired_output=Desired)
setDT(dt)[, date := as.Date(date)]

从头开始调整:

dt[, output:= sapply(date, function(x) sum(table(industry[between(date, x - lubridate::years(1), x)]) ^ 2)), 
   by = c("country")]
dt
   id       date industry country desired_output output
1:  1 2016-01-02        A      UK              1      1
2:  2 2017-01-01        A      UK              4      4
3:  3 2017-01-03        B      UK              3      3
4:  4 2017-01-03        C      UK              3      3
5:  5 2017-01-04        A      UK              6      6
6:  6 2017-01-03        A      US              1      1