[Rcpp-devel] Testing for existence of named components

Romain Francois romain at r-enthusiasts.com
Thu Mar 29 19:12:29 CEST 2012


Le 28/03/12 13:56, Ulrich Bodenhofer a écrit :
> Hi,
>
> My question is the following: is there any way of checking in whether a
> component of an Rcpp list (or vector) with a given name exists in this
> list. If I simply try accessing a non-existing component, I get an
> "index out of bounds" error. Trying to catch a possible exception did
> not work either. I also browsed the Rcpp package source code, but
> unfortunately I got lost. Sorry if this has been addressed on this list
> before. At least I googled in many different ways, but could not find
> anything. Any ideas? Any help is gratefully appreciated!
>
> Thanks and best regards,
> Ulrich

Hello,

I commited the has_element_called method on the Vector template (vectors 
of all sorts, incl lists).

For example:

require(Rcpp)
require(inline)

fx <- cxxfunction( signature( x_ = "list" ), '
     List x(x_) ;
     bool has_foo = x.has_element_called( "foo" ) ;
     Rprintf( "has(foo) = %d\\n", has_foo ) ;

     bool has_bar = x.has_element_called( "bar" ) ;
     Rprintf( "has(bar) = %d\\n" , has_bar) ;

     return R_NilValue  ;
', plugin = "Rcpp" )

x <- list( foo = 2, bla = 1:10 )
fx( x )


For the curious amongst you, the code looks like this :

     /**
      *  Does this vector have an element with the target name
      */
     bool has_element_called( const char* target ) const {
         SEXP names = RCPP_GET_NAMES(m_sexp) ;
         if( Rf_isNull(names) ) return false ;
         int n = Rf_length(names) ;
         for( int i=0; i<n; i++){
             if( !strcmp( target, CHAR(STRING_ELT(names, i)) ) ) return 
true ;
         }
         return false ;
     }

It would be awesome if someone would contribute a unit test for this 
feature based on the inline snippet above.

Romain



-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
R Graph Gallery: http://addictedtor.free.fr/graphiques
blog:            http://romainfrancois.blog.free.fr
|- http://bit.ly/xbKv0R : Crawling facebook with R
|- http://bit.ly/v3WB8S : ... And now for solution 17, still using Rcpp
`- http://bit.ly/uaQDGr : int64: 64 bit integer vectors for R


More information about the Rcpp-devel mailing list