我想检查是否有任何预先存在的技巧 na.locf (从 zoo 包), rleinverse.rleRCpp?

我写了一个循环来实现,例如我做了实施 na.locf(x, na.rm=FALSE, fromLast=FALSE) 如下:

#include <Rcpp.h>
using namespace Rcpp;

//[[Rcpp::export]]
NumericVector naLocf(NumericVector x) {
  int n=x.size();
  for (int i=1;i<n;i++) {
    if (R_IsNA(x[i]) & !R_IsNA(x[i-1])) {
      x[i]=x[i-1];
    }
  }
  return x;
}

我只是想知道,由于这些是相当基本的功能,有人可能已经在 RCpp 以更好的方式(可能是避免循环)或更快的方式?

有帮助吗?

解决方案

我唯一要说的是你在测试 NA 每个值两次,当你只需要做一次。测试 NA 不是一个免费的操作。也许是这样的:

//[[Rcpp::export]]
NumericVector naLocf(NumericVector x) {
    int n = x.size() ;
    double v = x[0]
    for( int i=1; i<n; i++){
        if( NumericVector::is_na(x[i]) ) {
            x[i] = v ;
        } else {
            v = x[i] ;    
        }
    }

    return x;
}

然而,这仍然会做不必要的事情,比如设置 v 每次当我们只能做最后一次,我们看不到 NA.我们可以尝试这样的事情:

//[[Rcpp::export]]
NumericVector naLocf3(NumericVector x) {
    double *p=x.begin(), *end = x.end() ;
    double v = *p ; p++ ;

    while( p < end ){
        while( p<end && !NumericVector::is_na(*p) ) p++ ;
        v = *(p-1) ;
        while( p<end && NumericVector::is_na(*p) ) {
            *p = v ;
            p++ ;
        }
    }

    return x;
}

现在,我们可以尝试一些基准:

x <- rnorm(1e6)
x[sample(1:1e6, 1000)] <- NA 
require(microbenchmark)
microbenchmark( naLocf1(x), naLocf2(x), naLocf3(x) )
#  Unit: milliseconds
#       expr      min       lq   median       uq      max neval
# naLocf1(x) 6.296135 6.323142 6.339132 6.354798 6.749864   100
# naLocf2(x) 4.097829 4.123418 4.139589 4.151527 4.266292   100
# naLocf3(x) 3.467858 3.486582 3.507802 3.521673 3.569041   100
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top