Search code examples
rvectorsequenceseq

uncover an integer sequence where all but one values are masked by NA's


Say I have an integer vector where all but one entries are masked by NA's,

x <- c(NA, NA, 5, NA)

Is there a way to unmask those NA's (by in-place modification of NA or creating a new vector)? My desired output is

c(3, 4, 5, 6)

Solution

  • Could be

    id <- which(!is.na(x))
    newx <- seq_along(x) + (x[id] - id)
    

    This works for your all NA's but one value vector.