Reputation: 11480
Set every non-NA value that has a non-NA value to "his left" to NA
.
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
[1] 3 NA NA NA NA 1 NA NA 2 NA NA NA
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
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
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
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