Jellz
Jellz

Reputation: 455

Add each column to a new data frame

For example, I have a data frame with 4 columns: col1 col2 col3 col4

I would like to get a new data frame by accumulating each column: col1 col1+col2 col1+col2+col3 col1+col2+col3+col4

How should I write in R?

Upvotes: 1

Views: 62

Answers (3)

hello_friend
hello_friend

Reputation: 5798

Base R (not as efficient or clean as Ronak's) [using Henry's data]:

data.frame(Reduce(rbind, Map(cumsum, data.frame(t(startdf)))), row.names = NULL)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389355

In base R, you can calculate row-wise cumsum using apply.

Using @Henry's data :

startdf[] <- t(apply(startdf, 1, cumsum))
startdf

#  col1 col2 col3 col4
#1    1   21  321 4321
#2    4   34  234 1234

Upvotes: 4

Henry
Henry

Reputation: 6784

If this was a matrix then you could use rowCumsums from the matrixStats package

so starting with a dataframe and returning to a dataframe I suppose you could try something like

library(matrixStats)
startdf <- data.frame(col1=c(1,4), col2=c(20,30), 
                 col3=c(300,200), col4=c(4000,1000))
finishdf <- as.data.frame(rowCumsums(as.matrix(startdf)))

to go from

  col1 col2 col3 col4
1    1   20  300 4000
2    4   30  200 1000

to

  V1 V2  V3   V4
1  1 21 321 4321
2  4 34 234 1234

Upvotes: 2

Related Questions