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

John Chambers jmc at stat.stanford.edu
Fri Dec 3 00:34:15 CET 2010


Sorry, didn't see this before my last mail.  Looks like a better solution.

On 12/2/10 1:55 PM, Romain Francois wrote:
> Le 02/12/10 22:51, Romain Francois a écrit :
>> Le 02/12/10 22:40, Douglas Bates a écrit :
>>> 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.
>>>
>>> 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.
>>
>> I don't think we have this wheel. We could add a method like this in
>> RObject :
>>
>> bool inherits( const std::string& clazz ) ;
>>
>> This would be a neat addition.
>>
>> Romain
>
> And actually there is this in the R API:
>
> Rboolean Rf_inherits(SEXP, const char *);
>
>
> so we can simply write inherits as:
>
> inline bool inherits( const char* clazz ){
>     return ::Rf_inherits( m_sexp, clazz ) == TRUE ;
> }
>
> Can you try to add it and test it ?
>
> Romain
>


More information about the Rcpp-devel mailing list