[Rcpp-devel] Yet Another Design Question

Douglas Bates bates at stat.wisc.edu
Thu May 6 16:57:12 CEST 2010


On Wed, May 5, 2010 at 6:04 AM, Romain Francois
<romain at r-enthusiasts.com> wrote:
> Le 13/04/10 00:14, Douglas Bates a écrit :
>>
>> One of the advantages of using S4 classes and methods in R is that
>> there are formal definitions of classes.  I plan eventually to write R
>> code that will take an S4 class definition and create a C++ class
>> definition and constructor code to mirror the R class using Rcpp
>> templates.
>>
>> Right now my question is related to constructors.  If I have a slot in
>> an S4 class that is itself an S4 object, is there a way to chain the
>> constructor so that I generate the internal object without first
>> creating an empty object.
>>
>> To be specific, I have an S4 class "reModule" that contains sparse
>> matrices of S4 class "dgCMatrix" and some information that is atomic.
>> The S4 definition is (more-or-less)
>>
>> setClass("reModule", representation(Lambda = "dgCMatrix", Zt =
>> "dgCMatrix", theta = "numeric", Lind = "integer"))
>>
>> and the definition of dgCMatrix is
>>
>> setClass("dgCMatrix", representation(Dim = "integer", i = "integer", p
>> = "integer", x = "numeric")
>>
>> Using Rcpp I define C++ classes
>>
>> class dgCMatrix {
>> public:
>>     dgCMatrix(Rcpp::S4);
>>
>>     Rcpp::IntegerVector Dim, i, p;
>>     Rcpp::NumericVector x;
>> };
>>
>> class reModule {
>> public:
>>     reModule(Rcpp::S4);
>>
>>     dgCMatrix Lambda, Zt;
>>     Rcpp::NumericVector theta;
>>     Rcpp::IntegerVector Lind;
>> };
>>
>> If I define a constructor for the reModule without chaining to
>> constructors for the dgCMatrix objects then I need to define a
>> dgCMatrix::dgCMatrix() constructor and then redefine the Lambda and Zt
>> members inside the reModule constructor.  I think a more idiomatic C++
>> constructor definition is to chain to the other constructor as in
>>
>> using namespace Rcpp;
>>
>> reModule::reModule(S4 xp) :
>>     Lambda(S4(xp.slot("Lambda"))),
>>     Zt(S4(xp.slot("Zt"))),
>>     ...
>> {
>> }
>>
>> but the compiler doesn't like constructing an S4 object from an
>> Rcpp::RObject::SlotProxy.
>
> It should work now (rev 1171).

Thank you.

> Can I ask you to add an unit test in runit.S4.R for this.

Will do.

>> The way I have gotten around this is to use
>>    Lambda(S4(SEXP(xp.slot("Lambda"))))
>> etc.
>>
>> Is that a reasonable construction to use?
>
> --
> Romain Francois
> Professional R Enthusiast
> +33(0) 6 28 91 30 30
> http://romainfrancois.blog.free.fr
> |- http://bit.ly/9aKDM9 : embed images in Rd documents
> |- http://tr.im/OIXN : raster images and RImageJ
> |- http://tr.im/OcQe : Rcpp 0.7.7
>
>


More information about the Rcpp-devel mailing list