Home > Blockchain >  Is there a R function or better way to sum rows and columns cumulatively?
Is there a R function or better way to sum rows and columns cumulatively?

Time:02-03

Let´s suppose a data frame

df1 <- data.frame(A = c(1,2,3), B = c(4,5,6), C = c(7,8,9), D = c(10,11,12))

I want to sum both rows and columns cumulatively, like

mysum <- c(sum(df1[1,1:4]), 
       sum(df1[1:2,1:4]),
       sum(df1[1:3,1:4])
          )

Any thoughts to improve the code?. dplyr solution? R base? I have thousands of rows and columns. Thanks in advance

CodePudding user response:

How about:

mysum <- cumsum(rowSums(df1))

mysum
[1] 22 48 78
  •  Tags:  
  • Related