Reputation: 96
I would like to call from a C++ function defined using Rcpp and R function by passing a list of arguments, in a way similar to using do.call in R. Here is a silly example:
Suppose I have a vector and I want to compute a trimmed mean. Two possible ways are
x = rnorm(100)
mean(x, trim = 0.1)
do.call("mean", list(x = x, trim = 0.1))
In my specific case using do.call is preferable because it could be a list of several parameters to be used by the function to be called.
Based on some examples found in stackoverflow, I tried to implement the above in C++ as follows:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double foo(Function f, List args)
{
double out = as<double>(f(args));
return out;
}
The above code does not work if args is a list, but only if is a vector of values.
Any help would be appreciated.
LS
Upvotes: 3
Views: 785
Reputation: 522
I am not very sure if the below is what you expect.
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double foo (Function f, NumericVector x) {
double out = Rcpp::as<double>(f(x, Named("trim", 0.1)));
return out;
}
/*
> x = rnorm(100)
> do.call("mean", list(x = x, trim = 0.1))
[1] 0.1832635
> Rcpp::sourceCpp("test.cpp")
> foo(mean, x)
[1] 0.1832635
*/
Upvotes: 1