Andre Elrico
Andre Elrico

Reputation: 11480

Set consequent non na values to NA

Set every non-NA value that has a non-NA value to "his left" to NA.

Data

a <- c(3,2,3,NA,NA,1,NA,NA,2,1,4,NA)

[1]  3  2  3 NA NA  1 NA NA  2  1  4 NA

Desired Output

[1]  3 NA NA NA NA  1 NA NA  2 NA NA NA

My working but ugly solution:

IND   <- !(is.na(a)) & data.table::rleidv(!(is.na(a))) %>% duplicated
a[IND]<- NA
a

There's gotta be a better solution ...

Upvotes: 2

Views: 57

Answers (3)

Stephen Henderson
Stephen Henderson

Reputation: 6522

OK for brevity...

a[!is.na(dplyr::lag(a))]<-NA
a
[1]  3 NA NA NA NA  1 NA NA  2 NA NA NA

Upvotes: 2

Julius Vainora
Julius Vainora

Reputation: 48211

Alternatively,

a[-1][diff(!is.na(a)) == 0] <- NA; a
# [1]  3 NA NA NA NA  1 NA NA  2 NA NA NA

Upvotes: 4

Sotos
Sotos

Reputation: 51592

You can do a simple ifelse statement where you add your vector with a lagged vector a. If the result is NA then the value should remain the same. Else, NA, i.e.

ifelse(is.na(a + dplyr::lag(a)), a, NA)
#[1]  3 NA NA NA NA  1 NA NA  2 NA NA NA

Upvotes: 2

Related Questions