Adding columns sums in dataframe row wise

2019-07-19 17:17发布

问题:

I would like to add the sums of the columns of my dataframe one row at a time.

So for each row, I would like to compute the sum of the columns above it.

Is there an elegant way to do this with a combination of colSums and apply (or sapply, rollapply)? I have been trying a couple of combinations of those, but could not quite figure it out.

回答1:

new_df <- apply(data_frame, 2, cumsum)


回答2:

With dplyr, we can do

library(dplyr)
data %>%
      mutate_all(cumsum)