我正在使用如下所示的数据集处理 R:
test=data.frame("1991" = c(1,5,3), "1992" = c(4,3,3), "1993" = c(10,5,3), "1994" = c(1,1,1), "1995" = c(2,2,6))
test=plyr::rename(test, c("X1991"="1991", "X1992"="1992", "X1993"="1993", "X1994"="1994", "X1995"="1995"))
我想要做的是我想创建名为 Pre1991, Pre1992, Pre1993, ... 的变量,这些变量将存储该年的累积值,例如
Pre1991 = test$1991
Pre1992 = test$1991 + test$1992
Pre1993 = test$1991 + test$1992 + test$1993
很快。
我的真实数据集包含 1900-2017 年的变量,因此我无法手动执行此操作。我想写一个for循环,但它没有用。
for (i in 1900:2017){
x = paste0("Pre",i)
df[[x]] = rowSums(df[,(colnames(df)<=i)])
}
有人可以帮忙查看我的代码/建议其他方法吗?谢谢!
编辑1:
非常感谢!我想知道是否有办法可以反向使用 cumsum 函数?例如,如果我对特定年份之后发生的事情感兴趣:
Post1991 = test$1992 + test$1993 + test$1994 + test$1995 + ...
Post1992 = test$1993 + test$1994 + test$1995 + ...
Post1993 = test$1994 + test$1995 + ...