How to fill in the preceding numbers whenever there is a 0 in R?

前端 未结 5 1343
小蘑菇
小蘑菇 2021-02-13 18:19

I have a string of numbers:

n1 = c(1, 1, 0, 6, 0, 0, 10, 10, 11, 12, 0, 0, 19, 23, 0, 0)

I need to replace 0 with the corresponding number righ

5条回答
  •  隐瞒了意图╮
    2021-02-13 18:24

    Don't forget the simplicity and performance gain of Rcpp...

    Using Arun's sample size I get...

    Unit: milliseconds
                                      expr       min        lq    median        uq      max neval
                             rollValue(n1)  3.998953  4.105954  5.803294  8.774286 36.52492   100
     n1[cummax(seq_along(n1) * (n1 != 0))] 17.634569 18.295344 20.698524 23.104847 74.72795   100
    

    The .cpp file to source is simply...

    #include 
    using namespace Rcpp;
    
    // [[Rcpp::plugins("cpp11")]]
    
    // [[Rcpp::export]]
    NumericVector rollValue(const NumericVector v) {
      auto out = clone(v);
      auto tmp = v[0];
      for( auto & e : out) {
        if( e == 0 ) {
          e = tmp;
          continue;
        }
        tmp = e;
      }
      return out;
    }
    

提交回复
热议问题