Romain
April 05, 2017
350

# R and C++. Past Present and Future.

R and C++. Past Present and Future. Presented at the MilanoR meetup on 2017-04-05

April 05, 2017

## Transcript

1. ### R and C++ Past, Present and Future Romain François Consulting

Datactive romain@thinkr.fr @romain_francois
2. None
3. None
4. None

177

11. ### int add( int a, int b ){ return a +

b ; } > add( 40, 2 ) [1] 42

13. ### #include <R.h> #include <Rinternals.h> int add( int a, int b

){ return a + b ; } SEXP add_c( SEXP a_, SEXP b_ ){ int a = INTEGER(a_)[0], b = INTEGER(b_)[0] ; int res = add( a, b ) ; SEXP result = PROTECT(allocVector(INTSXP, 1) ) ; INTEGER(result)[0] = res ; UNPROTECT(1) ; return result ; }
14. ### add <- function(a, b){ .Call( "add_c", a, b ) }

> add( 40, 2 ) Error in add(33, 9) : INTEGER() can only be applied to a 'integer', not a 'double' > add( 40L, 2L ) [1] 42
15. ### add <- function(a, b){ .Call( "add_c", as.integer(a), as.integer(b) ) }

> add( 40, 2 ) [1] 42 > add( 40L, 2L ) [1] 42
16. ### Tools • SEXP • INTEGER • PROTECT • allocVector •

INTSXP • UNPROTECT • .Call • as.integer

18. ### #include <Rcpp.h> // [[Rcpp::export]] int add( int a, int b

){ return a + b ; } > add( 17L, 25L ) [1] 42 > add( 17, 25 ) [1] 42

20. None
21. ### ! weighted_mean_1 <- function(x, w) { total <- 0 total_w

<- 0 for (i in seq_along(x)) { total <- total + x[i] * w[i] total_w <- total_w + w[i] } total / total_w }

24. ### \$ #include <Rcpp.h> using namespace Rcpp ; // [[Rcpp::export]] double

weighted_mean_cpp( NumericVector x, NumericVector w){ int n = x.size() ; double total = 0.0 ; double total_w = 0.0 ; for( int i=0; i<n; i++){ total += x[i] * w[i] ; total_w += w[i] ; } return total / total_w ; }
25. None
26. None

31. ### Rcpp n + 2 core sugar modules core modules Rcpp

n +1 core sugar modules core modules Rcpp n core sugar modules core modules % mypkg ' ✔ \$ )

33. ### NumericVector IntegerVector CharacterVector Function sugar modules … IntegerVector CharacterVector Function

sugar NumericVector core core modules … core pkg1 pkg2 core pkg3 core CharacterVector IntegerVector NumericVector

35. ### Pros • Smaller • Faster • Robust • Controlled updates

Cons • More copies of code base • Maybe more testing
36. None