我想检查是否有任何预先存在的帽子戏法na.locf
(从zoo
包装),rle
并inverse.rle
在RCpp
?
我编写了一个循环来实现,例如,我做了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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句