How can I convert the following vector:
x <- c(0, 0, 0, 1, 0, 3, 2, 0, 0, 0, 5, 0, 0, 0, 8)
in the desired form:
y <- c(1, 1, 1, 1, 3, 3, 2, 5, 5, 5, 5, 8, 8, 8, 8)
Any idea would be greatly appreciated.
Here's another approach using only the R base:
idx <- x != 0 split(x, cumsum(idx) - idx) <- x[idx]
Now the x-vector:
x #[1] 1 1 1 1 3 3 2 5 5 5 5 8 8 8 8
you can use zooto fill in NA using the function na.locfas follows:
zoo
na.locf
zoo::na.locf(replace(x, x==0, NA), fromLast = TRUE) #[1] 1 1 1 1 3 3 2 5 5 5 5 8 8 8 8
rle, R.
rle
tmp <- rle(x) tmp$values[which(tmp$values == 0)] <- tmp$values[which(tmp$values == 0) + 1L] inverse.rle(tmp) [1] 1 1 1 1 3 3 2 5 5 5 5 8 8 8 8
, , 0. , head(which(tmp$values == 0), -1) which(tmp$values == 0), .
head(which(tmp$values == 0), -1)
which(tmp$values == 0)