How to copy a value in a vector to next position(s) in vector

后端 未结 5 1810
余生分开走
余生分开走 2021-01-19 02:45

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

5条回答
  •  悲&欢浪女
    2021-01-19 03:23

    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.

提交回复
热议问题