Anthony Hauser
Anthony Hauser

Reputation: 719

Run r function with C++ via Rcpp

Trying to understand more how Rcpp works, I runned this script:

// [[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);
}

in order to use R function into C++ with Rcpp. Here is the error message:

error: 'NumericVector' does not name a type.

I checked for Rtools and it is installed, so I don't understand why it is accepting NumericVector as a type name.

Upvotes: 0

Views: 277

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368539

You failed to - either add the line using namespace Rcpp; - or prefix the identifiers with Rcpp::; - you also failed to add the #include for Rcpp

This works:

#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);
}

In case you are unaware, Rcpp also has a vectorised Rcpp::rnorm() as a C++ function -- see documentation for Rcpp Sugar.

Upvotes: 1

Related Questions