Hi,
If I understand it correctly, what you like to do is set all values in a vector to "1" after the fist "1" appears. For example 0,0,1,0,1 becomes 0,0,1,1,1.
If that is the case, here are ways of doing that
#Base R implementation
myData = data.frame(
id = 1:10,
val = c(0,0,0,0,1,0,1,1,0,1)
)
pos = which(myData$val == 1)[1]
if(!is.na(pos)){
myData$val[pos:nrow(myData)] = 1
}
myData
#> id val
#> 1 1 0
#> 2 2 0
#> 3 3 0
#> 4 4 0
#> 5 5 1
#> 6 6 1
#> 7 7 1
#> 8 8 1
#> 9 9 1
#> 10 10 1
#Alternative solution
myData$val[
1:nrow(myData) >
min(which(myData$val == 1)[1], nrow(myData), na.rm = T)] = 1
Created on 2021-11-20 by the reprex package (v2.0.1)
#Tidverse implementation
library(dplyr)
myData = data.frame(
id = 1:10,
val = c(0,0,0,0,1,0,1,1,0,1)
)
myData = myData %>%
mutate(val = ifelse(
row_number() > min(which(val == 1)[1], n(), na.rm = T),
1, val))
myData
#> id val
#> 1 1 0
#> 2 2 0
#> 3 3 0
#> 4 4 0
#> 5 5 1
#> 6 6 1
#> 7 7 1
#> 8 8 1
#> 9 9 1
#> 10 10 1
Created on 2021-11-20 by the reprex package (v2.0.1)
Both cases use the which() function to find the positions that are "1", then takes the first value and from that position onwards set everything to 1. What makes the code a little more complicated is taking care of the scenario where everting is "0", in which case nothing has to be updated.