[Rcpp-devel] pass an R list as an argument and accessing elements of a list

Vinh Nguyen vinhdizzo at gmail.com
Fri Oct 8 06:41:06 CEST 2010

Dear Rcpp List,

My goal is to write a generic C++ optimizing function (call it "optim"
in this email) based on the Newton-Raphson algorithm.  I will be
passing into the optimizing function 4 arguments:
1.  (pointer to) a function, "f1", to be optimized,
2.  an initial value/vector,
3.  the remaining inputs (other data, say x, y, and z) that argument 1
needs in order to compute its value, derivative, and 2nd derivative,
for the optimization, and
4.  the final object to store the value, derivative, and 2nd derivative outputs.

As argument 1 will be different from case to case, so too will
argument 3.  In other words, the arguments to the function f1 will be
varying in terms of number and type (could be 2, 3, 4, ... number of
objects).  To be as flexible as possible, I'm thinking that argument 3
should be an R list.  Questions follow:

I'll pass the R list as an SEXP object and then use Rcpp to access that list:
extern "C" SEXP MyCppFunc(..., SEXP _list){
Rcpp::List list(_list) ;

Is the above the proper way to pass a list the Rcpp way?  I've
used Rcpp::List::create but haven't done passing a list as an

To access the elements of the list, can I access them as list["x"],
list["y"], and list["z"], just like the Rcpp::NumericVector case?
Don't think I saw accessing lists in the vignettes.

When I pass the Rcpp::List into the optim function, is this the
correct way to pass it:

void optim(..., Rcpp::List list){
// do stuff with list, such as list["x"].

-- Vinh

More information about the Rcpp-devel mailing list