Easy to do using match()
and numeric indices:
- use
match()
to find the first occurence of a non-NA value - use
which()
to convert the logical vector fromis.na()
to a numeric index - use that information to find the correct positions in x
Hence:
x <- c(NA,NA,NA,1,2,3,NA,NA,4,5,NA)
isna <- is.na(x)
nonna <- match(FALSE,isna)
id <- which(isna)
x[id[id>nonna]] <- 0
gives:
> x
[1] NA NA NA 1 2 3 0 0 4 5 0