Rcpp Version 0.12.12
newApiExample.r
Go to the documentation of this file.
1 #!/usr/bin/env r
2 
3 suppressMessages(library(Rcpp))
4 
5 # R function that will be called from C++
6 vecfunc <- function(x) {
7  y <- x^1.05 # do a transformation
8  print(y) # but also print
9  plot(y, ylim=c(1,8), type='b') # and even plot
10  Sys.sleep(0.225) # sleep before next call
11  return(y)
12 }
13 
14 ## NOTE: This is the old way to compile Rcpp code inline.
15 ## The code here has left as a historical artifact and tribute to the old way.
16 ## Please use the code under the "new" inline compilation section.
17 
18 suppressMessages(library(inline))
19 
20 # C++ source code to operate on function and vector
21 cpp <- '
22  int n = as<int>(N);
23  NumericVector numvec(xvec) ;
24  Function f(fun) ;
25  for( int i=0; i<n; i++){
26  numvec = f( numvec ) ;
27  }
28  return numvec ;
29 '
30 
31 # create a C++ function
32 funx <- cxxfunction(signature(N = "integer" , xvec = "numeric", fun = "function" ),
33  body=cpp, include = "using namespace Rcpp; ", plugin = "Rcpp")
34 
35 
36 ## NOTE: Within this section, the new way to compile Rcpp code inline has been
37 ## written. Please use the code next as a template for your own project.
38 
39 # C++ source code to operate on function and vector
40 cppFunction('
41 NumericVector funx(int n, NumericVector numvec, Function f){
42  for( int i = 0; i < n; i++ ){
43  numvec = f( numvec ) ;
44  }
45  return numvec ;
46 }')
47 
48 
49 # create the vector
50 xvec <- sqrt(c(1:12, 11:1))
51 
52 # set up x11
53 x11(width=3,height=3)
54 par(mar=c(3,3,1,1),cex=0.8, pch=19)
55 
56 # run example
57 funx( 10L, xvec, vecfunc )