## Rcpp 0.7.2

By romain francois on Wednesday, January 13 2010, 09:44 - Rcpp - Permalink

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 ;

## Comments

Wow this makes me look like I want to try out Rcpp as playing in C looks a lot simpler.

Out of curiosity, suppose I were to do a simulation with linear regression and record the coefficients and standard error. Would doing such a loop using Rcpp be a lot faster than the loop in R? That is, all the benefits of doing things in C are still there. I'm wondering because the linear regression function lm() is still being but in C instead of R now. Thanks!

Vinh

Hi,

you might want to start with using the much faster lm.fit when doing simulations, it is a bit more work than just using lm or glm but it pays off.

For the speed, I don't know, it is worth a shot. Note that Rcpp has its mailing list where more people (at least one more) would be able to answer this.

Romain

Oh yes, I keep forgetting about lm.fit and glm.fit. I guess the only extra step would be model.matrix(), something along the line of:

fit <- lm.fit(y, x=model.matrix(y~ x1+...+xn), weights=myweights)

Anyhow, my hypothetical question is meant to see the benefits of calling R functions in Rcpp. I was lazy and wanted to know the added benefits without trying it myself =).