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)
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)
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
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