我有以下data.frame:
grp nr yr
1: A 1.0 2009
2: A 2.0 2009
3: A 1.5 2009
4: A 1.0 2010
5: B 3.0 2009
6: B 2.0 2010
7: B NA 2011
8: C 3.0 2014
9: C 3.0 2019
10: C 3.0 2020
11: C 4.0 2021
所需的输出:
grp nr yr nr_roll_period_3
1 A 1.0 2009 NA
2 A 2.0 2009 NA
3 A 1.5 2009 NA
4 A 1.0 2010 NA
5 B 3.0 2009 NA
6 B 2.0 2010 NA
7 B NA 2011 NA
8 C 3.0 2014 NA
9 C 3.0 2019 NA
10 C 3.0 2020 NA
11 C 4.0 2021 3.333333
逻辑:
当前我具有此功能:
calculate_rolling_window <-
function(dt, date_col, calc_col, id, k) {
require(data.table)
return(setDT(dt)[, paste(calc_col, "roll_period", k, sep = "_") :=
ifelse(
( sapply(get(date_col), function(x) length(get(calc_col)[between(get(date_col), x - k + 1, x)])) < k ) |
( sapply(get(date_col), function(x) anyNA(get(calc_col)[between(get(date_col), x - k + 1, x)])) ),
NA_real_,
sapply(get(date_col), function(x) mean(get(calc_col)[between(get(date_col), x - k + 1, x)]))
),
by = mget(id)][order(get(id), get(date_col)),])
}
对于常规情况(在日期列中没有重复项),它可以正常工作。但是,如果重复,则失败:
grp nr yr nr_roll_period_3
1: A 1.0 2009 1.500000
2: A 2.0 2009 1.500000
3: A 1.5 2009 1.500000
4: A 1.0 2010 1.375000
5: B 3.0 2009 NA
6: B 2.0 2010 NA
7: B NA 2011 NA
8: C 3.0 2014 NA
9: C 3.0 2019 NA
10: C 3.0 2020 NA
11: C 4.0 2021 3.333333
关于如何处理此问题的任何想法?无需专门的data.table
方法。
答案 0 :(得分:4)
这可以通过将分组为非等额联接来解决,以汇总长度为k
的滚动窗口,连续k
过滤,并加上更新加入:
library(data.table)
k <- 3L
# group by join parameters of a non-equi join
mDT <- setDT(DT)[.(grp = grp, upper = yr, lower = yr - k),
on = .(grp, yr <= upper, yr > lower),
.(uniqueN(x.yr), mean(nr)), by = .EACHI]
# update join with filtered intermediate result
DT[mDT[V1 == k], on = .(grp, yr), paste0("nr_roll_period_", k) := V2]
DT
返回OP的预期结果:
grp nr yr nr_roll_period 1: A 1.0 2009 NA 2: A 2.0 2009 NA 3: A 1.5 2009 NA 4: A 1.0 2010 NA 5: B 3.0 2009 NA 6: B 2.0 2010 NA 7: B NA 2011 NA 8: C 3.0 2014 NA 9: C 3.0 2019 NA 10: C 3.0 2020 NA 11: C 4.0 2021 3.333333
中间结果mDT
包含V2
期间的滚动平均值k
和每个期间内唯一/不同年份V1
的计数。它是由DT
的非等联接与一个包含上限和下限的data.table创建的,该表是由.(grp = grp, upper = yr, lower = yr - k)
即时创建的。>
mDT
grp yr yr V1 V2 1: A 2009 2006 1 1.500000 2: A 2009 2006 1 1.500000 3: A 2009 2006 1 1.500000 4: A 2010 2007 2 1.375000 5: B 2009 2006 1 3.000000 6: B 2010 2007 2 2.500000 7: B 2011 2008 3 NA 8: C 2014 2011 1 3.000000 9: C 2019 2016 1 3.000000 10: C 2020 2017 2 3.000000 11: C 2021 2018 3 3.333333
此过滤器将针对包含精确k
不同年的行进行过滤:
mDT[V1 == k]
grp yr yr V1 V2 1: B 2011 2008 3 NA 2: C 2021 2018 3 3.333333
最后,它与DT
结合在一起,将新列附加到DT
。
请注意,如果输入数据中有mean()
,则NA
默认返回NA
。
library(data.table)
DT <- fread(text = "rn grp nr yr
1: A 1.0 2009
2: A 2.0 2009
3: A 1.5 2009
4: A 1.0 2010
5: B 3.0 2009
6: B 2.0 2010
7: B NA 2011
8: C 3.0 2014
9: C 3.0 2019
10: C 3.0 2020
11: C 4.0 2021", drop = 1L)