I have a vector that looks something like this:
c(0.5,0,0,0,0,0.7,0,0,0,0,0.4,0,0,0,0)
Suppose I want to copy the values on positions 1, 6
Here's one way:
zero.locf <- function(x) {
if (x[1] == 0) stop('x[1] should not be 0')
with(rle(x), {
no.0 <- replace(values, values == 0, values[(values == 0) - 1])
rep(no.0, lengths)
})
}
x <- c(0.5,0,0,0,0,0.7,0,0,0,0,0.4,0,0,0,0)
zero.locf(x)
# [1] 0.5 0.5 0.5 0.5 0.5 0.7 0.7 0.7 0.7 0.7 0.4 0.4 0.4 0.4 0.4
rle(x)
returns a list
with items values
and lengths
.
rle(x)
Run Length Encoding
lengths: int [1:6] 1 4 1 4 1 4
values : num [1:6] 0.5 0 0.7 0 0.4 0
with
opens up this list
and lets us reference these entries directly.