Search code examples
rradix

Index TRUE occurrences preserving NA in a new vector


I have what some of you might categorise as a dumb question, but I cannot solve it. I have this vector:

a <- c(NA,NA,TRUE,NA,TRUE,NA,TRUE)

And I want to get this in a new vector:

b <- c(NA,NA,1,NA,2,NA,3)

That simple. All the ways I am trying do not preserve the NA and I need them untouched. I would prefer if there would be a way in base R.


Solution

  • In base R, use cumsum() while excluding the NA values:

    a <- c(NA,NA,TRUE,NA,TRUE,NA,TRUE)
    
    a[!is.na(a)] <- cumsum(a[!is.na(a)])
    

    Output:

    [1] NA NA  1 NA  2 NA  3