Data:
df1 <- structure(c(0.0253076925223279, 0.026982250093938, 0.0255870113592418,
0.0192848154638279, 0.0250068916940005, 0.0371223276107671, 0.022485625943609,
0.0263385169691969, 0.0245475669733608, 0.024996036491309, 0.110756640575203,
0.117002581734862, 0.111806739597355, 0.087279930906384, 0.109622045843623,
0.152408007275128, 0.099957642537113, 0.114615545866446, 0.10788200628028,
0.10958102836925, 0.681515597151481, 0.683203057980559, 0.681859981632574,
0.665865681988598, 0.681114547367163, 0.679833115543316, 0.676373141080783,
0.682658703710392, 0.680439471581149, 0.681099476906173, 0.138975227724712,
0.132020686077446, 0.137767089458977, 0.170991690168057, 0.140299086491158,
0.100956535058728, 0.152417417783121, 0.134613991456593, 0.142367678603227,
0.140347311335879, 0.0434448420262756, 0.0407914241131952, 0.0429791779518519,
0.056577881473133, 0.0439574286040558, 0.0296800145120611, 0.0487661726553738,
0.0417732419973719, 0.044763276561984, 0.0439761468973889), .Dim = c(10L,
5L), .Dimnames = list(c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "10"), c("1", "2", "3", "4", "5")))
Now I want df2
, I want the columns to have cumulative values. I can of course do this manually:
df2 <- as.data.frame(df1)
library(data.table)
df2 <- setDT(df2)[, `2`:=rowSums(df1[1:2])]
df2 <- setDT(df2)[, `3`:=rowSums(df1[2:3])]
df2 <- setDT(df2)[, `4`:=rowSums(df1[3:4])]
df2 <- setDT(df2)[, `5`:=rowSums(df1[4:5])]
But I would like to be able to do this automatically without specifying the number of columns manually, by using something like ncol(df2)
.
What would be the best way to do this?