I was trying to call the sd(x), which is a R function, in Rcpp. I've seen an example of calling the R function dbate(x) in Rcpp and it works perfectly.
// dens calls the pdf of beta distribution in R
//[[Rcpp::export]]
double dens(double x, double a, double b)
{
return R::dbeta(x,a,b,false);
}
But when I tired to apply this method to sd(x) as following, it went wrong.
// std calls the sd function in R
//[[Rcpp::export]]
double std(NumericVector x)
{
return R::sd(x);
}
Does anyone know why this doesn't work?
There are a few issues with your code.
std
is related to the C++ Standard Library namespace
error: redefinition of 'std' as different kind of symbol
R::
is a namespace that deals with Rmath functions. Other R
functions will not be found in within this scope.Rcpp::Environment
and Rcpp::Function
as given in the example sd_r_cpp_call()
.
With this being said, let's talk code:
#include <Rcpp.h>
//' @title Accessing R's sd function from Rcpp
// [[Rcpp::export]]
double sd_r_cpp_call(const Rcpp::NumericVector& x){
// Obtain environment containing function
Rcpp::Environment base("package:stats");
// Make function callable from C++
Rcpp::Function sd_r = base["sd"];
// Call the function and receive its list output
Rcpp::NumericVector res = sd_r(Rcpp::_["x"] = x,
Rcpp::_["na.rm"] = true); // example of additional param
// Return test object in list structure
return res[0];
}
// std calls the sd function in R
//[[Rcpp::export]]
double sd_sugar(const Rcpp::NumericVector& x){
return Rcpp::sd(x); // uses Rcpp sugar
}
/***R
x = 1:5
r = sd(x)
v1 = sd_r_cpp_call(x)
v2 = sd_sugar(x)
all.equal(r,v1)
all.equal(r,v2)
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With