【发布时间】:2020-02-08 14:33:38
【问题描述】:
我正在尝试构建一个特定于组的变量:
- 在满足条件之前进行观察。
- 满足条件时的第一次观察不适用。
- 对于后续观察,为满足条件时上次观察的值。
下面是 MWE。我正在寻找构建“last_value”的代码。我更喜欢使用 data.table(或 dplyr)来实现可扩展性/性能,但我愿意接受其他建议。谢谢!
library(data.table)
data.table(
group = c(rep("alpha", 4), rep("beta", 3)),
time = c(1:4, 1:3),
condition = c("Yes", "No", "Yes", "No", "No", "Yes", "No"),
value = 1:7,
last_value = c(NA, 1, 1, 3, NA, NA, 6))
# group time condition value last_value
# 1: alpha 1 Yes 1 NA
# 2: alpha 2 No 2 1
# 3: alpha 3 Yes 3 1
# 4: alpha 4 No 4 3
# 5: beta 1 No 5 NA
# 6: beta 2 Yes 6 NA
# 7: beta 3 No 7 6
# last_value is:
# NA in the 1st row as that is the 1st observation for group "alpha"
# 1 in the 2nd row as the 1st observation is condition = "Yes"
# 1 in the 3rd row as the 1st observation is condition = "Yes"; 2nd observation is condition = "No"
# 3 in the 4rd row as the 3rd observation is condition = "Yes"
# NA in the 5th row as that is the 1st observation for group "beta"
# NA in the 6th row as there is no prior observation with condition = "Yes"
# 6 in the 7th row as the 6th observation is condition = "Yes"
【问题讨论】:
标签: r data.table