我正在尝试在R中创建一组累积因子变量。我df
有4个时间的假人治疗:
id t1 t2 t3 t4
1 0 0 0 1
2 1 0 0 0
3 0 0 0 1
4 0 1 0 0
5 1 0 0 0
我想要的是一组按时间划分的累积处理变量(在以下示例中称为tc),如下所示:
id tc1 tc2 tc3 tc4
1 0 0 0 1
2 1 1 1 1
3 0 0 0 1
4 0 1 1 1
5 1 1 1 1
我已经尝试过该cumsum
函数,但是我不知道如何为因子变量处理该函数。关于如何执行此操作的任何想法?
一种方法是尝试使用该matrixStats::rowCummaxs
函数,但您需要先转换为该函数matrix
。虽然,通过你的数据结构来看,我会建议有工作matrix
,而不是data.frame
摆在首位
data1[-1] <- matrixStats::rowCummaxs(as.matrix(data1[-1]))
data1
# id t1 t2 t3 t4
# 1 1 0 0 0 1
# 2 2 1 1 1 1
# 3 3 0 0 0 1
# 4 4 0 1 1 1
# 5 5 1 1 1 1
或apply
逐行的方法(也将转换为matrix
)
data1[-1] <- t(apply(data1[-1], 1, cummax))
或@joran暗示-我们可以尝试进行长/宽转换
library(data.table)
dcast(melt(setDT(data1),
id = "id"
)[, value := cummax(value),
by = id],
id ~ variable)
# id t1 t2 t3 t4
# 1: 1 0 0 0 1
# 2: 2 1 1 1 1
# 3: 3 0 0 0 1
# 4: 4 0 1 1 1
# 5: 5 1 1 1 1
或者
library(dplyr)
library(tidyr)
data1 %>%
gather(variable, value, -id) %>%
group_by(id) %>%
mutate(value = cummax(value)) %>%
spread(variable, value)
# Source: local data frame [5 x 5]
# Groups: id [5]
#
# id t1 t2 t3 t4
# (int) (int) (int) (int) (int)
# 1 1 0 0 0 1
# 2 2 1 1 1 1
# 3 3 0 0 0 1
# 4 4 0 1 1 1
# 5 5 1 1 1 1
或@alexis_laz的有趣替代方法是pmax
使用Reduce
data1[-1] <- Reduce(pmax, data1[-1], accumulate = TRUE)
data1
# id t1 t2 t3 t4
# 1 1 0 0 0 1
# 2 2 1 1 1 1
# 3 3 0 0 0 1
# 4 4 0 1 1 1
# 5 5 1 1 1 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句