我有以下数据框:
df <- data.frame(type = c("planes", "trains", "automobiles"), t1 = c(4, 5, 6), t2 = c(20, 60, 24), t3 = c(100, 120, 72), t4 = c(800, 360, 144))
df
type t1 t2 t3 t4
1 planes 4 20 100 800
2 trains 5 60 120 360
3 automobiles 6 24 72 144
我现在想编写一个函数来转换 3:5 列以在每一行上运行聚合(例如,t2 = t1+t2 和 t3 = t1+t2+t3),这样我的新数据框看起来像这样:
new_df
type t1 t2 t3 t4
1 planes 4 24 124 924
2 trains 5 65 185 545
3 automobiles 6 30 102 246
最佳答案
您可以使用 apply
执行此操作,在对每一行调用 cumsum
后用结果替换数据框的相关部分。
df[-1] <- t(apply(df[-1], 1, cumsum))
df
# type t1 t2 t3 t4
# 1 planes 4 24 124 924
# 2 trains 5 65 185 545
# 3 automobiles 6 30 102 246
关于在 R 中跨列运行聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30496131/