I previously asked about column-wise replacement but got errors when row-wise replacing values with NA. I have the follow 'test' data frame in R with rows of binary values (0, 1). I would like to find the first incidence of 1 in each row and replace all subsequent values with NA.
> [,1] [,2] [,3] [,4] [,5] [,6] [,7]
> [1,] 0 0 0 0 0 0 0
> [2,] 1 1 1 0 0 1 1
> [3,] 0 1 0 0 0 0 0
test should become:
> [,1] [,2] [,3] [,4] [,5] [,6] [,7]
> [1,] 0 0 0 0 0 0 0
> [2,] 1 NA NA NA NA NA NA
> [3,] 0 1 NA NA NA NA NA
Following other posts I tried including rowwise() and within mutate() I included c_across() but got an error with the follow code:
> test %>% rowwise() %>%
> mutate(c_across(everything(), \(x) replace(x, cummax(x) & cummax(lag(x, default = 0)), NA)))
Again, thanks for your help.