你可以用一個簡單的RCPP實現一個小的性能改進:
library(Rcpp)
library(microbenchmark)
withinR <- function(x,y) x >= y[1] & x <= y[2]
cppFunction("LogicalVector withinCpp(const NumericVector& x, const NumericVector& y) {
double min = y[0], max = y[1];
int n = x.size();
LogicalVector out(n);
for(int i = 0; i < n; ++i) {
double val = x[i];
if (NumericVector::is_na(val)) {
out[i] = NA_LOGICAL;
} else {
out[i] = val >= min & val <= max;
}
}
return out;
}")
x <- sample(100, 1e5, rep = T)
stopifnot(all.equal(withinR(x, c(25, 50)), withinCpp(x, c(25, 50))))
microbenchmark(
withinR(x, c(25, 50)),
withinCpp(x, c(25, 50))
)
C++版本是4倍左右我的電腦上更快。如果你想要使用更多的Rcpp技巧,你可以進一步調整它,但這看起來已經很快了。即使是R版本也需要在可能出現瓶頸之前非常頻繁地調用。
# Unit: microseconds
# expr min lq median uq max
# 1 withinCpp(x, c(25, 50)) 635 659 678 1012 27385
# 2 withinR(x, c(25, 50)) 1969 2031 2573 2954 4082
你的意思是'y'總是一個二元向量,'y [1]
juba
2013-02-21 12:53:14
函數(...){return(...)}'=>'函數(...)...' – 2013-02-21 12:56:57
您可能需要'&'而不是'&&'。 – Roland 2013-02-21 12:59:53