R: column reference to itself -


please, help! have w:

x   y 0   0 0   0 0   0 0   1 0   0 0   0 0   -1 0   0 0   0 0   1 0   0 0   -1 0   0 0   0 

i get:

x   y 0   0 0   0 0   0 1   1 1   0 1   0 0   -1 0   0 0   0 1   1 1   0 0   -1 0   0 0   0 

i use r:

for (i in 2:length(w$x)) { w$x[i] = w$x[i-1] + w$y[i]} 

is possible without use of loop statement?

thank you!

this assumes want start initial value of 0 in x column:

transform(w, x = cumsum(y)) ##    x  y ## 1  0  0 ## 2  0  0 ## 3  0  0 ## 4  1  1 ## 5  1  0 ## 6  1  0 ## 7  0 -1 ## 8  0  0 ## 9  0  0 ## 10 1  1 ## 11 1  0 ## 12 0 -1 ## 13 0  0 ## 14 0  0 

otherwise can include initial value:

transform(w, x = x[1] + cumsum(y)) 

the result here same. both of these assume either y[1] zero, or want use actual value if nonzero (your code ignores y[1]).


Comments