Rcpp

Testing newly installed Rcpp

This is a quick test Rcpp module to ensure Rcpp was installed and linked properly to R.  Just run these lines of code in R and the answer should be 9 at the end. 

library(Rcpp)
library(inline)
fx <- cxxfunction(,"",includes=
  ' double add(double c,double d)
   {     double e=0;
         e=c+d;
         return e;
   }
RCPP_MODULE(foo)
   {  function( "add", &add ) ;}
 ', plugin="Rcpp")
foo <- Module("foo",getDynLib(fx))

foo$add(4,5)    #answer is 9

Quick look ups

//  is the format for adding comments in Rcpp

int n= b.size();    //finds the length of a vector b

int m=B.nrow();  //finds the number of rows in a matrix

double x=runif(1)(0);  //gets one random Uniform(0,1);  runif returns a vector so we just use element (0).

pow(), not ^, for exponentiation.

sqrt() and exp()  work

for a function that returns nothing use   void func_name(int a){  return; } 

Rbinom (rbinomint)

Wraps R.rbinom for correct input and output

   double rbinomint(int a, int b, double c)
   {   Rcpp::NumericVector x = rbinom(a,b,c);
       return x(0);
   }

Rnorm (rnormdouble)

Wraps R.rnorm for correct input and output.

   double rnormdouble(int a, double b, double c)
   {   Rcpp::NumericVector x = rnorm(a,b,c);
       return x(0);
   }

Sum a vector (sumv)

This is the same as the R function sum when used on a vector.

double sumv(Rcpp::NumericVector A)
   {    int na= A.size();
         double b=0;
         for (int i = 0; i < na; i++)
         { b=b+A(i);
         }
         return b;
   }

Multiply matrices (matmul)

In R this would be A%*%B.  In Rcpp it is matmul(A,B).

### Calls function: dot

Rcpp::NumericMatrix matmul(Rcpp::NumericMatrix A,Rcpp::NumericMatrix B)
   {     int a= A.nrow();
         int b= B.ncol();
         Rcpp::NumericMatrix C(a,b);
         for (int i = 0; i < a; i++)
         {  for (int j = 0; j < b; j++)
            {   C(i,j)= dot(A(i,_),B(_,j));
            }
         }
         return C;
   }

Pages