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

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

    Here's another base R approach. Initial zeros are left as is:

    v = c(0,1,2,-2.1,0,3,0,0.4,0,0)
    v[v!=0] = diff(c(0, v[v!=0]))
    cumsum(v)
    # [1]  0.0  1.0  2.0 -2.1 -2.1  3.0  3.0  0.4  0.4  0.4
    

    And here are some benchmarks:

    roland = function(v) {v[v == 0] <- NA; na.locf(v)}
    mp = function(x) {with(rle(x), rep(replace(values, values==0, values[which(values == 0)-1]), lengths))}
    quant = function(dat) {not.0 <- (dat != 0); approx(which(not.0), dat[not.0], xout = seq(along.with = dat), method = "constant", rule = 2)}
    eddi = function(v) {v[v!=0] = diff(c(0, v[v!=0])); cumsum(v)}
    
    v = sample(c(-10:10, 0), 1e6, TRUE)
    microbenchmark(roland(v), mp(v), quant(v), eddi(v), times = 10)
    #Unit: milliseconds
    #      expr      min       lq   median       uq      max neval
    # roland(v) 595.1630 625.7692 638.4395 650.4758 664.9224    10
    #     mp(v) 410.8224 433.6775 469.9346 496.6328 528.3218    10
    #  quant(v) 646.1775 753.0684 759.9805 838.4281 883.3383    10
    #   eddi(v) 265.8064 286.2922 316.7022 339.0333 354.0836    10
    

提交回复
热议问题