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

后端 未结 5 1806
余生分开走
余生分开走 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条回答
  •  梦毁少年i
    2021-01-19 03:31

    Here is an alternative using approx

    dat   <- c(0.5,0,0,0,0,0.7,0,0,0,0,0.4,0,0,0,0)
    not.0 <- (dat != 0)
    approx(which(not.0), dat[not.0], xout = seq(along.with = dat), method = "constant", yleft = 0, rule = 1:2)
    # $x
    # [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
    #
    # $y
    # [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
    

    And here is an alternative that relies on the stated structure of the initial vector (repetitions of a non-zero value followed by 4 zeros). It adresses the speed issue but at the cost of flexibility.

    dat <- c(0.5,0,0,0,0,0.7,0,0,0,0,0.4,0,0,0,0)
    rep(dat[seq(1, length(dat), by = 5)], each = 5)
    

提交回复
热议问题