Tags

,

It comes in handy when we can use R functions in our Perl scripts sometimes. So how could we do that?
Here is an exmaple:

Say we want to wrap the R function phyper(), dhyper(), ppois() and atan() as a Perl module named “rmath”,
first we need to create a file (here I named it as “rmath.in”) with the following content:

%module rmath
%{
       double phyper (double x, double NR, double NB, double n, int lower_tail, int log_p) ;
       double dhyper (double x, double NR, double NB, double n, int log_p) ;
       double ppois(double x, double lambda, int lower_tail, int log_p) ;
       double atan(double x) ;
%}
       double phyper (double x, double NR, double NB, double n, int lower_tail, int log_p) ;
       double dhyper (double x, double NR, double NB, double n, int log_p) ;
       double ppois(double x, double lambda, int lower_tail, int log_p) ;
       double atan(double x) ;

We will use swig (http://www.swig.org/) to wrap it. In Mac OSX, we can simply install it using homebrew (http://brew.sh/).


# install swig with homebrew
brew install swig

We need to download a temporary copy of R for compiling the standalone Rmath library.


# download R 
wget https://cran.r-project.org/src/base/R-3/R-3.2.1.tar.gz
tar xvzf R-3.2.1.tar.gz
ln -s R-3.2.1 R
cd R
./configure --prefix=/<Path to this temporary R>/R
cd ./src/nmath/standalone
make
make install

Now we use swig to wrap the R functions that we need into Perl modules.

swig -perl rmath.i 

rm *.o 
for f in *.c ; 
do 
gcc -I. -I../../../src/include -I../../../src/include -I./.. -I/usr/local/include -DHAVE_CONFIG_H -DMATHLIB_STANDALONE -arch x86_64 -g -O2 -std=gnu99 -c $f -o ${f/.c/.o} `perl -MExtUtils::Embed -e ccopts`;
ls -l ${f/.c/.o}; 
done rm sunif.o; 

gcc -bundle -flat_namespace -undefined dynamic_lookup -o rmath.bundle *.o
sudo cp rmath.bundle  /usr/local/ActivePerl-5.18/site/lib/ 
sudo cp rmath.pm  /usr/local/ActivePerl-5.18/site/lib/ 

Note: I am using ActivePerl-5.18 here since ActivePerl-5.22 doesn’t work for this for some reason.

References
https://cran.r-project.org/doc/manuals/r-release/R-admin.html#The-standalone-Rmath-library

Advertisements