Home > Software design >  Index TRUE occurrences preserving NA in a new vector
Index TRUE occurrences preserving NA in a new vector

Time:05-28

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.

CodePudding user response:

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

CodePudding user response:

Using replace from base R

b <- replace(a, !is.na(a), seq_len(sum(a, na.rm = TRUE)))
b
[1] NA NA  1 NA  2 NA  3

Or slightly more compact option (if the values are logical/numeric)

cumsum(!is.na(a)) * a
[1] NA NA  1 NA  2 NA  3

Update

If the OP's vector is

a <- c(NA,NA,TRUE,NA,FALSE,NA,TRUE)
 (a|!a) * cumsum(replace(a, is.na(a), 0))
[1] NA NA  1 NA  1 NA  2

CodePudding user response:

replaceing the non-NAs with the cumsum.

replace(a, !is.na(a), cumsum(na.omit(a)))
# [1] NA NA  1 NA  2 NA  3
  • Related