【发布时间】:2021-03-04 09:53:22
【问题描述】:
我有按“日期”排序的数据,其中一些值是“x”和它们的累积最大值“cmx”。我想创建一个列'max_date',它是每个累积最大值内第一行的日期。稍加改动:当有多个“x”值等于当前累积最大值时,应为这些行中的每一行选择一个新的“最大日期”。
注释了两个不同的cummax的一些数据:
d = structure(list(date = structure(c(18690, 18691, 18692, 18693, 18694, 18695, 18696, 18697), class = "Date"),
x = c(18, 70, 57, 94, 94, 13, 98, 23),
cmx = c(18, 70, 70, 94, 94, 94, 98, 98)),
row.names = c(NA, -8L), class = c("data.table", "data.frame"))
d
# date x cmx
# 1: 2021-03-04 18 18
# 2: 2021-03-05 70 70 # first row of cummax 70: select this date for row 2 & 3
# 3: 2021-03-06 57 70 #
# 4: 2021-03-07 94 94 # first row of cummax 94
# 5: 2021-03-08 94 94 # x is equal to cummax 94 again!
# 6: 2021-03-09 13 94 # I.e. row 5 is a 'new' first date to be used for row 5 & 6
# 7: 2021-03-10 98 98
# 8: 2021-03-11 23 98
因此,期望的结果:
# date x cmx max_date
# 1: 2021-03-04 18 18 2021-03-04
# 2: 2021-03-05 70 70 2021-03-05
# 3: 2021-03-06 57 70 2021-03-05
# 4: 2021-03-07 94 94 2021-03-07
# 5: 2021-03-08 94 94 2021-03-08
# 6: 2021-03-09 13 94 2021-03-08
# 7: 2021-03-10 98 98 2021-03-10
# 8: 2021-03-11 23 98 2021-03-10
我以为我可以使用frollapply,但无法让滚动窗口查看之前的所有行。
【问题讨论】:
-
frollapply 默认查看之前的行,不像 zoo 的 rollapply
标签: r data.table