Find the index position of the first non-NA value in an R vector?

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

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)

Tags:

R