Sample or Rmultinom (sampling)
By tholscla on Sat, 11/02/2013 - 10:49Draw one of {1,..,K} with probabilities "probf"
Needs function: sumv
Draw one of {1,..,K} with probabilities "probf"
Needs function: 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;
}
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;
}
###### 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))
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
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).
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;
}
This is a plot I made and used quite a bit. The input is a matrix of residuals (subject x number of MCMC iterations) coming from MCMC. Here is how I made this plot.
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?
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().