R

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;
   }

Generic wrapper

###### Libraries
library(Rcpp)
library(inline)

###### wrapper
fx <- cxxfunction(,"",includes=
  '
**********FILL FUNCTIONS IN HERE************
RCPP_MODULE(foo)
   {   function( "functionname1", &functionname1 ) ;
       function( "functionname2", &functionname2 ) ;
   }
', plugin="Rcpp")
foo <- Module("foo",getDynLib(fx))

 

Plot: quick reference

Things I find myself needing often:

box()                                 draws a box around the figure

par(mar=c(4,4,4,4))           can reset the margins for (bottom, left, top, right)

par(cex=2)                        makes all of the axis labels larger

par(mfrow=c(3,4))             makes panes in the Figure (rows,columns)

legend(100,28,legend=c("Mean","95% PI","95% PI"),col=c("blue","red","green"),lwd=c(1,1,2), lty=c(1,2,3))

segments(x0,y0,x1,y1)       adds line segments to a plot

Plot: 2D distribution plots with bands

This code adds estimated bands to 2D plots.  This can be used if you have posterior draws for two parameters (ie. from MCMC).  Estimated confidence bands of any level can be specified; the default is 68% and 95%.  This function takes some time; if you have a lot of points you may want to thin them before plotting (ie. use every 25th).

Dot product (dot)

Multiply two vectors together using a dot product.

double dot(Rcpp::NumericVector c,Rcpp::NumericVector d)
   {     int nc= c.size();
         double e=0;
         for (int i = 0; i < nc; i++)
         {  e=e+c(i)*d(i); }
         return e;
   }

R Code

This is what I do all day.  I write R code.  I am not a programmer. 

What other code would you like to seen shared here?

3D arrays

Seemlessly pass three dimensional arrays between between R and Rcpp.  I found a function called threeDIndex on a forum written for Rcpp  but it did not convert from R to  Rcpp smoothly. I needed to be passing these 3D arrays back and forth not just using them in Rcpp.  I re-wrote the threeDIndex code (mythreeDIndex code) that works seemlessly with the R coverterts c() and array().

Pages