This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Dataframe accumulative cell addition into new column

Hey guys, quite new here and to programming in general. I had to make a cummulative column out of another column in my dataframe and I couldn't find help on the mattar. So after I came on a sollution I thought it would be better to post this.

My initial thought was as follows:

```R
   x<- as.numeric(c("", 
                 as.numeric(Tom.VS.Hagai.R1[2,4]), 
                 sum(as.numeric(Tom.VS.Hagai.R1[2:3,4])),
                 sum(as.numeric(Tom.VS.Hagai.R1[2:4,4])),
                 sum(as.numeric(Tom.VS.Hagai.R1[2:5,4])),
                 sum(as.numeric(Tom.VS.Hagai.R1[2:6,4])),
                 sum(as.numeric(Tom.VS.Hagai.R1[2:7,4])),
                 sum(as.numeric(Tom.VS.Hagai.R1[2:8,4]))))

x
Tom.VS.Hagai.R1$Accumulative.Dead<-x
```

After wrapping my head on the matter this is the final product:

```R
> # 2 column 4 row dataframe, first row character second row numeric
> name<- c("Tom", "Hagai", "Yoni", "Aviv")
> apples<- c(1, 2, 3, 4)
> DF<- data.frame(name, apples)
> DF
   name apples
1   Tom      1
2 Hagai      2
3  Yoni      3
4  Aviv      4
> 
> # Looping
> # y is a vector place holder for the "for" loop
> # i is a running index set to run from 1 to the length of the data.frame's column number 2.
> # in the loop, append, appends the sum of 1 to i in column 2 of the data.frame.
> 
> y<-c()
> for( i in 1:length(DF[,2])){
+   y<- append(y, sum(DF[1:i,2]))
+ }
> 
> # Next we load the new vector y as a third column of the datafre:
> DF$accumulative<- y
> DF
   name apples accumulative
1   Tom      1            1
2 Hagai      2            3
3  Yoni      3            6
4  Aviv      4           10
```

Hope it helped someone somewhere, enjoy.

(edited: Spelling mistake in heading)

r

did you try cumsum ? @ tiriyon

> name<- c("Tom", "Hagai", "Yoni", "Aviv")
> apples<- c(1, 2, 3, 4)
> DF<- data.frame(name, apples)
> DF$cumsum=cumsum(DF$apples)
> DF
   name apples cumsum
1   Tom      1      1
2 Hagai      2      3
3  Yoni      3      6
4  Aviv      4     10

Hey, that looks much easier, I saw the comment on stackoverflow first so added it as answer; thanks for the help!

1 answer

Found out that

cumsum(DF$apples)

would have done the job simpler.

Via stackoverflow comment:

[...] what you needed was cumsum(DF$apples). – Ronak Shah

Log in to answer this question.