Modification of a Vector based on elements sequence

Viewed 232

How is it possible to transform the following vector:

x <- c(0, 0, 0, 1, 0, 3, 2, 0, 0, 0, 5, 0, 0, 0, 8)

into the desired form:

y <- c(1, 1, 1, 1, 3, 3, 2, 5, 5, 5, 5, 8, 8, 8, 8)

Any idea would be highly appreciated.

3 Answers

you can use zoo to fill NAs via na.locf function as follows,

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

Here's another approach using only base R:

idx <- x != 0
split(x, cumsum(idx) - idx) <- x[idx]

The x-vector is now:

x
#[1] 1 1 1 1 3 3 2 5 5 5 5 8 8 8 8

Using rle, you can do the following in base R.

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

Note that this assumes the final value is not 0. If this is not the case, you could use head(which(tmp$values == 0), -1) in place of which(tmp$values == 0) to drop the final value.

Related