[Rcpp-devel] accessing list elements without using names
On Fri, Feb 10, 2012 at 3:30 PM, Dirk Eddelbuettel <edd at debian.org> wrote:
On 10 February 2012 at 15:05, Douglas Bates wrote: | Or if you want to show off you could collapse it to | | > src <- " | + ? NumericMatrix tmpMatrix(as<SEXP>(List(L)[0])); | + ? return wrap(tmpMatrix.ncol()); | + " | > f <- cxxfunction(signature(L="list"), src, plugin = "Rcpp" ) | > f(list(matrix(1:9,3,3))) | [1] 3 Nice. The as<> cast is a good idea, it may even work with as<NumericMatrix> which would avoid the ugly SEXP in user code ...
IIRC it doesn't work because you need to "de-proxy" the returned
element from the list before you can pass it to some instantiation of
"as".
By the way, this use of the as<SEXP> actually has a practical use. I
have a class C++ glmFamily which corresponds to the R "family" class
for glm and related functions. It is a good practice to initialize
class data members before the body of the constructor function and it
took me a while to work out
class glmFamily {
protected:
std::string d_family, d_link; /**< as in the R glm family */
//@{ R functions from the family, as a fall-back
Rcpp::Function d_devRes, d_linkfun, d_linkinv, d_muEta, d_variance, d_aic;
//@}
Rcpp::Environment d_rho;
public:
glmFamily(Rcpp::List);
...
};
glmFamily::glmFamily(List ll)
: d_family( as<std::string>(as<SEXP>(ll["family"]))),
d_link( as<std::string>(as<SEXP>(ll["link"]))),
d_devRes( as<SEXP>(ll["dev.resids"])),
d_linkfun( as<SEXP>(ll["linkfun"])),
d_linkinv( as<SEXP>(ll["linkinv"])),
d_muEta( as<SEXP>(ll["mu.eta"])),
d_variance(as<SEXP>(ll["variance"])),
d_aic( as<SEXP>(ll["aic"])),
d_rho( d_devRes.environment()) {
if (!ll.inherits("family"))
throw std::runtime_error("glmFamily requires a list of (S3) class
\"family\"");
if (!lnks.count("identity")) initMaps();
}