A fast and natural interface to R from Perl

zaki
Wed, 24 Dec 2014 01:43:15 +0000
c programming language, code, pdl, perl module, perl programming language, r programming language, statistics

Love R? Love Perl? Well, I've got a nice little present for you this echo $(calendar) 1 season! Now you can pass data in and out of R as easily as

use v5.16;
use Statistics::NiceR;
use Data::Frame::Rlike;
Moo::Role->apply_roles_to_package( q|Data::Frame|, qw(Data::Frame::Role::Rlike) );

my $r = Statistics::NiceR->new;
my $iris = $r->get('iris');

say "Subset of Iris data set";
say $iris->subset( sub { # like a SQL WHERE clause
                  ( $_->('Sepal.Length') > 6.0 )
                & ( $_->('Petal.Width')  < 2   )
        })->select_rows(0, 34); # grab the first and last rows

which outputs

Subset of Iris data set
-----------------------------------------------------------------------
      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width  Species
-----------------------------------------------------------------------
 51   7             3.2          4.7           1.4          versicolor
 147  6.3           2.5          5             1.9          virginica
-----------------------------------------------------------------------

This is possible due to Statistics::NiceR and Data::Frame.

Statistics::NiceR is a C-level binding to the R interpreter that exposes all of R's functions as if they were Perl functions. It handles all the magic data conversion in the background so that you don't have to think about it.

Data::Frame is a container for PDL typed arrays that lets you think in terms of tabular data just like R's data.frames. It even prints out a table using Text::Table::Tiny. To support categorical data just like R's factor variables, it has a PDL subclass that keeps track of the levels of the data.

It's still an early release, so there may still be some kinks to figure out, but give it a try and be sure to ping me if there is something wrong.

Much thanks to the folks in #inline for helping out with very cool Inline::Module so that this code could hit CPAN (ingy++, ether++). You should definitely check it out as an alternative to writing XS.

There are already several interfaces to R on CPAN, but this is the first one that embeds R and provides a flexible data conversion mechanism. Hope you enjoy using it!

1. calendar(1) ↩