I'm trying to programmatically change a variable from a 0
to a 1
if there are three 1
s before and after a 0
.
For example, if the number in a vector were 1
, 1
, 1
, 0
, 1
, 1
, and 1
, then I want to change the 0
to a 1
.
Here is data in the vector dummy_code
in the data.frame
df
:
original_df <- data.frame(dummy_code = c(1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1))
Here is how I'm trying to have the values be recoded:
desired_df <- data.frame(dummy_code = c(1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1)
I tried to use the function fill
in the package tidyr
, but this fills in missing values, so it won't work. If I were to recode the 0
values to be missing, then that would not work either, because it would simply code every NA
as 1
, when I would only want to code every NA
surrounded by three 1s
as 1
.
Is there a way to do this in an efficient way programmatically?