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

后端 未结 5 1813
余生分开走
余生分开走 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:36

    I'd probably loop through every single element greater 0 using lapply, then apply rep function to repeat each of these values 5 times and merge the resulting list entries via do.call("c", ...).

    do.call("c", lapply(which(tmp > 0), function(i) rep(tmp[i], 5)))
    [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
    

提交回复
热议问题