Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rcpp - Define a C++ function that takes an R function and an ellipsis argument

Tags:

c++

r

ellipsis

rcpp

I have an R function bar that takes another R function foo, defined as follows:

foo <- function(x,y) x + y
bar <- function(foo, z, ...) z + foo(...)

A call to bar would be of the form:

bar(foo, 1,2,3)

Now with foo defined as above, I want to create a C++ version of bar. Here's what I've tried:

library(Rcpp)
cppFunction(
'
  double bar(Function foo, double z, ...) {
  return z + foo(...);
 }
 ')

This clearly doesn't work. What would be the right way to define this function in C++?

Thanks.

like image 975
user3294195 Avatar asked Sep 03 '25 15:09

user3294195


1 Answers

It might be easier to turn your ellipsis into a list before feeding it to Rcpp

bar <- function(foo, z, ...) {
   args <- list(...)
   bar_internal(foo, z, args)
}

And then your Rcpp function can simply take a Rcpp::List instead of ellipsis.

double bar_internal(Function foo, double z, List args){

}
like image 86
Jeroen Ooms Avatar answered Sep 05 '25 03:09

Jeroen Ooms