[英]Updating column values based on previous values (once treated always treated)
I am wondering if there was a much faster way using data.table/dplyr to replace values based on previous values by group.我想知道是否有更快的方法使用 data.table/dplyr 按组替换基于先前值的值。
Suppose my original data table looks like:假设我的原始数据表如下所示:
DT_orig <- data.table(name = c("A", "A", "A", "B", "B", "B"),
year = c("2001", "2002", "2003", "2001", "2002", "2003"),
treat = c(1,0,0, 0,0,1))
This looks as follows:这看起来如下:
name year treat
1: A 2001 1
2: A 2002 0
3: A 2003 0
4: B 2001 0
5: B 2002 0
6: B 2003 1
Here, for each individual(name) and time period (year), there is a column (treat) which indicates whether or not they have been assigned a treatment.在这里,对于每个人(姓名)和时间段(年),有一列(治疗)指示他们是否已被分配治疗。
I am considering an alternative treatment where once an individual is treated, the individual remains treated.我正在考虑另一种治疗方法,即一旦一个人接受治疗,该人就会继续接受治疗。 Thus, the modified data table should look like:因此,修改后的数据表应如下所示:
name year treat
1: A 2001 1
2: A 2002 1
3: A 2003 1
4: B 2001 0
5: B 2002 0
6: B 2003 1
Notice that for person A, being treated in 2001 implies that they are "treated" in the following years as well.请注意,对于 A 人,在 2001 年接受治疗意味着他们在接下来的几年也受到“治疗”。
Because I have a very large data table, I was wondering if there was a very quick way of modifying achieving this.因为我有一个非常大的数据表,我想知道是否有一种非常快速的修改方法来实现这一点。
May be we can use cummax
(from base R
)也许我们可以使用cummax
(来自base R
)
DT_orig[, treat := cummax(treat), name]
DT_orig
# name year treat
#1: A 2001 1
#2: A 2002 1
#3: A 2003 1
#4: B 2001 0
#5: B 2002 0
#6: B 2003 1
Or the same can be done with dplyr
或者同样可以用dplyr
来完成
library(dplyr)
DT_orig %>%
group_by(name) %>%
mutate(treat = cummax(treat))
Or using base R
或使用base R
DT_orig$treat <- with(DT_orig, ave(treat, name, FUN = cummax))
I would use cummax()
but here is an alternative illustrating data.table
's join syntax:我会使用cummax()
但这里有一个替代说明data.table
的连接语法:
DT_orig[, year := as.integer(year)]
DT_orig[DT_orig[treat == 1], on = .(year >= year, name), treat := 1L]
name year treat
1: A 2001 1
2: A 2002 1
3: A 2003 1
4: B 2001 0
5: B 2002 0
6: B 2003 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.