运行 通过 Rcpp 使用 C++ 的 r 函数

Run r function with C++ via Rcpp

为了进一步了解 Rcpp 的工作原理,我运行了这个脚本:

// [[Rcpp::export]]
NumericVector my_fun(){
// calling rnorm()
Function f("rnorm");   

// Next code is interpreted as rnorm(n=5, mean=10, sd=2)
return f(5, Named("sd")=2, _["mean"]=10);
}

为了使用 Rcpp 将 R 函数用于 C++。 这是错误消息:

error: 'NumericVector' does not name a type.

我检查了 Rtools 并安装了它,所以我不明白为什么它接受 NumericVector 作为类型名称。

你失败了 - 添加行 using namespace Rcpp; - 或在标识符前加上 Rcpp::; - 您也未能为 Rcpp

添加 #include

这个有效:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector my_fun(){
  // calling rnorm()
  Function f("rnorm");   

  // Next code is interpreted as rnorm(n=5, mean=10, sd=2)
  return f(5, Named("sd")=2, _["mean"]=10);
}

如果您不知道,Rcpp 也有一个向量化的 Rcpp::rnorm() 作为 C++ 函数——请参阅 Rcpp Sugar 的文档。