[Rcpp-devel] idiom for determining the (S3) class of an R object?

John Chambers jmc at stat.stanford.edu
Fri Dec 3 00:32:26 CET 2010


There is a related routine in R_HOME/src/main/attrib.c:

EXP R_data_class(SEXP obj, Rboolean singleString)
{
     SEXP value, klass = getAttrib(obj, R_ClassSymbol);
     int n = length(klass);
     if(n == 1 || (n > 0 && !singleString))
     return(klass);
     if(n == 0) {
     SEXP dim = getAttrib(obj, R_DimSymbol);
     int nd = length(dim);

This is designed to handle S3 or S4 and with the second argument to get 
the single string needed.  It is not in the API, unfortunately, but it 
is called rather directly from the primitive that  implements class().  
Worth consulting at least.

John

On 12/2/10 1:51 PM, Dirk Eddelbuettel wrote:
> On 2 December 2010 at 15:40, Douglas Bates wrote:
> | I currently use constructions like
> |
> | 	if (as<string>(lst.attr("class")) != "family")
> | 	    throw std::runtime_error("glmFamily requires a list of (S3) class
> | \"family\"");
> |
> | Is there a cleaner way that I haven't discovered yet.
>
> Seems correct as the reverse of how we set classes via attr.
>
> | This method is error-prone because the S3 class of an object is a
> | CharacterVector whose length can be greater than 1, so the check
> | should compare against the individual strings in that vector until it
> | finds a match or runs out of elements.
> |
> | It is not a great challenge to write a short function that will return
> | a boolean given an object and a target class as a std::string, but I
> | would prefer not to reinvent the wheel unless I need to.
>
> That looks like a useful helper function to have :)
>
> Dirk
>


More information about the Rcpp-devel mailing list