Find the index position of the first non-NA value in an R vector?
Use a combination of is.na
and which
to find the non-NA index locations.
NonNAindex <- which(!is.na(z))
firstNonNA <- min(NonNAindex)
# set the next 3 observations to NA
is.na(z) <- seq(firstNonNA, length.out=3)
Similar idea to that of @Joshua, but using which.min()
## dummy data
set.seed(1)
dat <- runif(10)
dat[seq_len(sample(10, 1))] <- NA
## start of data
start <- which.min(is.na(dat))
which gives:
> (start <- which.min(is.na(dat)))
[1] 4
Use this to set start:(start+2)
to NA
is.na(dat) <- seq(start, length.out = 3)
resulting in:
> dat
[1] NA NA NA NA NA
[6] NA 0.94467527 0.66079779 0.62911404 0.06178627
If dealing with large data, Position
is considerably faster than which
, because it only evaluates until a match is found, rather than evaluating the whole vector.
x=c(rep(NA,3),1:1e8)
Position(function(x) !is.na(x), x)
# 4
We can assign NA to the following N values (or the end of the vector, whichever comes first) by
pos = Position(function(x)!is.na(x), x)
x[pos:min(pos+N-1, length(x))] <- NA