(This article was first published on Romain Francois, Professional R Enthusiast, and kindly contributed to R-bloggers)
Rcpp 0.7.2 is out, checkout Dirk's blog for details
selected highlights from this new version:
character vectors
if one wants to mimic this R code in C
> x <- c( "foo", "bar" )one ends up with this :
SEXP x = PROTECT( allocVector( STRSXP, 2) ) ; SET_STRING_ELT( x, 0, mkChar( "foo" ) ) ; SET_STRING_ELT( x, 1, mkChar( "bar" ) ) ; UNPROTECT(1) ; return x ;
Rcpp lets you express the same like this :
CharacterVector x(2) ; x[0] = "foo" ; x[1] = "bar" ;
or like this if you have GCC 4.4 :
CharacterVector x = { "foo", "bar" } ;
environments, functions, ...
Now, we try to mimic this R code in C :rnorm( 10L, sd = 100 )You can do one of these two ways in Rcpp :
Environment stats("package:stats") ;
Function rnorm = stats.get( "rnorm" ) ;
return rnorm( 10, Named("sd", 100 ) ) ;
or :
Language call( "rnorm", 10, Named("sd", 100 ) ) ;
return eval( call, R_GlobalEnv ) ;
and it will get better with the next release, where you will be able to just call call.eval() and stats["rnorm"].
Using the regular R API, you'd write these liks this :
SEXP stats = PROTECT( R_FindNamespace( mkString("stats") ) ) ;
SEXP rnorm = PROTECT( findVarInFrame( stats, install("rnorm") ) ) ;
SEXP call = PROTECT( LCONS( rnorm, CONS(ScalarInteger(10), CONS(ScalarReal(100.0), R_NilValue)))) ;
SET_TAG( CDDR(call), install("sd") ) ;
SEXP res = PROTECT( eval( call, R_GlobalEnv ) );
UNPROTECT(4) ;
return res ;
or :
SEXP call = PROTECT( LCONS( install("rnorm"), CONS(ScalarInteger(10), CONS(ScalarReal(100.0), R_NilValue)))) ;
SET_TAG( CDDR(call), install("sd") ) ;
SEXP res = PROTECT( eval( call, R_GlobalEnv ) );
UNPROTECT(2) ;
return res ;
To leave a comment for the author, please follow the link and comment on his blog: Romain Francois, Professional R Enthusiast.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

Zero Inflated Models and Generalized Linear Mixed Models with R.
Zuur, Saveliev, Ieno (2012).