以下代码:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector FFF(){
NumericVector LB(3);
LB[0]=Language("max",12.3,1.2,13.3,34,10,12.45).eval();
LB[1]=Language("min",12.31,1.24,13.35,340,109,121.45).eval();
LB[2]=Language("sum",12.37,1.21,13.43,34).eval();
return LB;
}
不会通过编译器,因为“语言(”max“,12.3,1.2,13.3,34,10,12.45).eval())”返回SEXP对象,它不适合LB [0]' s型“双”。我真的想直接使用R base中的max(),min()和sum()而不是编写额外的C ++函数。你有什么好主意吗?
谢谢!
答案 0 :(得分:10)
这是 Rcpp Sugar
的完美用例http://dirk.eddelbuettel.com/code/rcpp/Rcpp-sugar.pdf
http://adv-r.had.co.nz/Rcpp.html#rcpp-sugar
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector FFF(){
NumericVector LB(3);
LB[0] = max(NumericVector::create(12.3,1.2,13.3,34,10,12.45));
LB[1] = min(NumericVector::create(12.31,1.24,13.35,340,109,121.45));
LB[2] = sum(NumericVector::create(12.37,1.21,13.43,34));
return LB;
}
答案 1 :(得分:9)
我喜欢Eigen:
// [[Rcpp::depends(RcppEigen)]]
#include <RcppEigen.h>
using namespace Rcpp;
using Eigen::Map;
using Eigen::VectorXd;
typedef Map<VectorXd> MapVecd;
// [[Rcpp::export]]
NumericVector RcppEigenFun(NumericVector xx) {
const MapVecd x(as<MapVecd>(xx));
NumericVector LB(3);
LB[0] = x.minCoeff();
LB[1] = x.maxCoeff();
LB[2] = x.sum();
return LB;
}
使用它:
RcppEigenFun(3:7)
#[1] 3 7 25
这是使用糖的相应功能:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector RcppFun(NumericVector x) {
NumericVector LB(3);
LB[0] = min(x);
LB[1] = max(x);
LB[2] = sum(x);
return LB;
}
基准:
set.seed(42)
x <- rnorm(1e5)
library(microbenchmark)
microbenchmark(RcppEigenFun(x), RcppFun(x))
#Unit: microseconds
# expr min lq median uq max neval
# RcppEigenFun(x) 101.425 101.807 101.948 102.1785 123.095 100
# RcppFun(x) 1480.187 1480.552 1480.889 1489.0045 1550.173 100