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
0
solved R: transforming one column to another [closed]