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

Romain Francois romain at r-enthusiasts.com
Thu Dec 2 22:55:28 CET 2010


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

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/hovakS : RcppGSL initial release
|- http://bit.ly/iaxTdO : parser 0.0-12
`- http://bit.ly/gnCl01 : Rcpp 0.8.9




More information about the Rcpp-devel mailing list