0

I want to calculate the value in a row as the sum of value of the previous row and a value of another column:

timestamp = c(1:10) 
c1 = c(0, 1, 0, 0, -1, 0 ,1 ,0, -1, 0)
c2 = c(rep(0,10)) 

df = data.frame(timestamp, c1, c2)      

#df$c2 is then set to the desired result
df$c2 <- c(0, 1, 1, 1, 0, 0, 1, 1, 0, 0) 

> df
   timestamp c1 c2
1          1  0  0
2          2  1  1
3          3  0  1
4          4  0  1
5          5 -1  0
6          6  0  0
7          7  1  1
8          8  0  1
9          9 -1  0
10        10  0  0

Of course I don't want to use a for loop. I found a lot of examples using apply but could not find a solution when referencig another column (c1 in the example)

Cath
  • 23,906
  • 5
  • 52
  • 86
giannic
  • 91
  • 5

2 Answers2

0

In c3 you can find c1+c1(pos-1)+c2, is this what you want?

c0<-c(0,as.numeric(df[c(1:nrow(df)-1),"c1"]))
c3<-c0+df$c1+df$c2

cbind(df,c3)
   timestamp c1 c2 c3
1          1  0  0  0
2          2  1  1  2
3          3  0  1  2
4          4  0  1  1
5          5 -1  0 -1
6          6  0  0 -1
7          7  1  1  2
8          8  0  1  2
9          9 -1  0 -1
10        10  0  0 -1
Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39
0

Or with dplyr :

library(dplyr)
df %>% mutate( c2 = cumsum(c1))