-9

I have the following vector:

v <- c(2L, 2L, NA, NA, NA, NA, 8L, NA)

How can I replace missing values with the value of the previous series + 1 so it becomes:

c(2L, 2L, 3L, 3L, 3L, 3L, 8L, 9L)
Cath
  • 23,906
  • 5
  • 52
  • 86
Philippe Massicotte
  • 1,321
  • 12
  • 24

2 Answers2

5

As mentioned, zoo has a last-observation-carried-forward function. We can add one to it:

library(zoo)
v2 <- na.locf(v) 
v2[is.na(v)] <- v2[is.na(v)] + 1L
#[1] 2 2 3 3 3 3 8 9
Pierre L
  • 28,203
  • 6
  • 47
  • 69
0

Its not pretty or efficient but it gets the answer you want. Hopefully someone else will be able to post some nicer code but this should get you started.

v <- c(2L, 2L, NA, NA, NA, NA, 8L, NA)
last <- NA
vec <- vector()
for (i in 1:length(v)) {
    cur <- v[i]
    if (! is.na(cur) ) {
        val <- cur
        last <- cur
    }
    else  val <- last + 1
    vec[i] <- val
}

vec
gowerc
  • 1,039
  • 9
  • 18
  • I should have been more specific. You are right, it is easy to do with a loop. Was wondering if there was an elegant solution with dplyr or another package. – Philippe Massicotte Jun 29 '16 at 13:06