List

Today I figured out something cool: how to use R from within Mathematica. I had generated some data from a model and wanted to compute inequality metrics such as the Gini coefficient and the Theil index. Unfortunately, these metrics are not implemented in Mathematica. In R, there is the ineq package which comes with functions to compute these metrics. Usually I would have either implemented the inequality metrics in Mathematica, or I would have saved my data to disk, imported it into R, computed the inequality metrics, saved to disk, and re-imported them into Mathematica. Quite a tedious procedure. Now bring in RLink for Mathematica. Using it, one can simply call R from within Mathematica and directly use the results.

Now, I am on Ubuntu 14.04 and the Mathematica help did not really guide me in how to get RLink to run. With the help of stackexchange and some experimentation I figured it out. Here are the lines to make it work.

The strange thing here is that my R version is actually 3.1.1 but if I specified that, I could not get it to work. Now, how did I compute the inequality metrics?

First, we need to load the ‘ineq’ library using

Next, suppose that I have the data on which I want to compute the metrics in a Mathematica list called wagedat. I assign it to an object in R using

Finally, the inequality metric is computed using

where everything between “” is a standard R command. The requested value is returned directly into Mathematica and I can use it in further computations. Very cool!