R 因子变量累计和
我试图在R中创建一组累积因子变量。我的R 因子变量累计和,r,dataframe,R,Dataframe,我试图在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
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
函数,但需要先转换为矩阵。不过,从您的数据结构来看,我建议首先使用矩阵
而不是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
或者正如@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
或
或者通过@alexis_laz使用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
data1[-1]一种方法是尝试使用matrixStats::rowCummaxs
函数,但需要先转换为矩阵。不过,从您的数据结构来看,我建议首先使用矩阵
而不是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
或者正如@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
或
或者通过@alexis_laz使用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
data1[-1]max.col
救援:
df[-1][col(df[-1]) >= max.col(df[-1], ties.method="first")] <- 1
df
# 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
max.col
救援:
df[-1][col(df[-1]) >= max.col(df[-1], ties.method="first")] <- 1
df
# 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
可能另一个主要的方法是融化/收集数据,并实际有时间作为显式变量。@joran,是的,我可能也会添加这一点。感谢您对备选方案的支持并支持您的矩阵转换评论:tail(Reduce(pmax,DF[-1L],init=integer(nrow(DF)),accumulate=TRUE),-1L)
用as.data.frame
包装,或者更好的是,class@alexis_laz哇,真不错。你不想把它贴成你自己的吗?@alexis_laz你真的不需要init
在这里,不是吗?我已经简化了您的解决方案-请参见编辑。另一种主要的方法可能是融化/收集数据,并实际有时间作为显式变量。@joran,是的,我可能也会添加它。感谢您对备选方案的支持并支持您的矩阵转换评论:tail(Reduce(pmax,DF[-1L],init=integer(nrow(DF)),accumulate=TRUE),-1L)
用as.data.frame
包装,或者更好的是,class@alexis_laz哇,真不错。你不想把它贴成你自己的吗?@alexis_laz你真的不需要init
在这里,不是吗?我已经简化了您的解决方案-请参见编辑。感谢对代码的详细解释,它非常有用。感谢对代码的详细解释,它非常有用。