0

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.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
R Camp
  • 31
  • 1
  • Error messages are usually very helpful to understand problems - what error did you get? The way your data prints looks like a `matrix` not a `data.frame`. Could you share your sample data reproducibly with `dput()` so we can see the data structure? (`dput(your_data[1:3, ])` will make a copy/pasteable version of the first 3 rows of `your_data` including all the data structure information.) – Gregor Thomas May 18 '23 at 19:19

1 Answers1

0

First need an object to work on:

M <- matrix( scan(text="0 0 0 0 0 0 0   
 1 1 1 0 0 1 1   
 0 1 0 0 0 0 0"), 3,7, byrow=TRUE)

Need to transpose what would otherwise appear to be self-documenting code because apply returns the row-applied values as columns.

t(apply(M, 1,    # work on rows of M
     function(r){ if( any(r==1)){   # skip lines with all 0
                   r[ (which(r==1)[1]+1):7 ]  <- NA} #modify others
                   r}))
     [,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
IRTFM
  • 258,963
  • 21
  • 364
  • 487