Anatolye Anatolye - 3 months ago 11
R Question

R: transforming one column to another

Please, help me! I've got:

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


I need:

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


There is 1 in column x fill y with 1 forward until there is -1 in column x from where fill y with 0.

Is it possible to do it without using a loop statement?

It is not "R: column reference to itself".
Using cumsum it is not possible get the answer.

Answer

This should work if your logic is whenever there is 1 in column x fill y with 1 forward until there is -1 in column x from where fill y with 0 and vice versa:

Since you are trying to fill forward vectors with previous values, you may want to use na.locf(last observation carried forward) function from zoo package and set up threshold values before filling forward, which is the first line doing: set the value to be 1 when x == 1 and 0 when x == -1 and otherwise set it to be NA for na.locf to work properly. The first element will be an exception from your output, it seems that you want the default to be zero if none of 1 and -1 exist, and that is what the second line is doing here. After setting up the threshold in the y column, filling it forward would be straight forward with na.locf:

df$y <- with(df, ifelse(x == 1, 1, ifelse(x == -1, 0, NA)))
df$y[1] <- if(df$x[1] != 1) 0 else df$y[1]
df$y <- zoo::na.locf(df$y)

df
#     x y
# 1   0 0
# 2   0 0
# 3   1 1
# 4   0 1
# 5   0 1
# 6   1 1
# 7   0 1
# 8   0 1
# 9  -1 0
# 10  0 0
Comments