(This article was originally published at Lindons Log » Statistics, and syndicated at StatsBlogs.)
Needed to generate draws from an inverse Gaussian today, so I wrote the following Rcpp code:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
Col<double> rrinvgauss(int n, double mu, double lambda){
Col<double> random_vector(n);
double z,y,x,u;
for(int i=0; i<n; ++i){
z=R::rnorm(0,1);
y=z*z;
x=mu+0.5*mu*mu*y/lambda - 0.5*(mu/lambda)*sqrt(4*mu*lambda*y+mu*mu*y*y);
u=R::runif(0,1);
if(u <= mu/(mu+x)){
random_vector(i)=x;
}else{
random_vector(i)=mu*mu/x;
};
}
return(random_vector);
}
It seems to be faster than existing implementations such as rig from mgcv and rinvgauss from statmod packages.
library(Rcpp)
library(RcppArmadillo)
library(rbenchmark)
library(statmod)
library(mgcv)
sourceCpp("rrinvgauss.cpp")
n=10000
benchmark(rig(n,1,1),rinvgauss(n,1,1),rrinvgauss(n,1,1),replications=100)
rename rrinvgauss as desired.
The post Generate Random Inverse Gaussian in R appeared first on Lindons Log.
Please comment on the article here: Lindons Log » Statistics

