I have a string of numbers:
n1 = c(1, 1, 0, 6, 0, 0, 10, 10, 11, 12, 0, 0, 19, 23, 0, 0)
I need to replace 0 with the corresponding number righ
Because rle
is the answer to everything:
#make an example including an NA value
n1 <- c(1, 1, 0, 6, NA, 0, 10, 10, 11, 12, 0, 0, 19, 23, 0, 0)
r <- rle(n1)
r$values[which(r$values==0)] <- r$values[which(r$values==0)-1]
inverse.rle(r)
# [1] 1 1 1 6 NA NA 10 10 11 12 12 12 19 23 23 23
A version that skips NA
s would be:
n1 <- c(1, 1, 0, 6, NA, 0, 10, 10, 11, 12, 0, 0, 19, 23, 0, 0)
r <- rle(n1[!is.na(n1)])
r$values[which(r$values==0)] <- r$values[which(r$values==0)-1]
n1[!is.na(n1)] <- inverse.rle(r)
n1
# [1] 1 1 1 6 NA 6 10 10 11 12 12 12 19 23 23 23