A simple example.
Calling Python from within R via the R-package rPython is fairly easy. However, very little documentation exists on this package, and some of the commands may appear quirky at first. Also, don’t confuse rPython with RPython (see capitals)! The paucity of written documentation on this package seems to scare away many biologists, who – if they are like me – prefer to work with well-documented code. But fear not!
Usage of rPython is straightforward with a bit of exercise. The following tutorial is intended to give a quick and simple example on how to work with rPython.
> library(rPython)
Loading required package: RJSONIO
I use the command python.exec() to execute basically any Python operation within R.
# Generating a dictionary in Python
> python.exec("capcities = {'sk':'Slovakia','de':'Germany',
'hu':'Hungary'}")
I use the command python.get() to assign a new variable in R with a value from Python.
# Pulling the dictionary from Python into R
> abbrev_dict = python.get("capcities")
> abbrev_dict
sk de hu
"Slovakia" "Germany" "Hungary"
Note, however, that python.get() is very inflexible in what it can retrieve from Python.
> abbrevs = python.get("capcities.keys()")
Traceback (most recent call last):
...
TypeError: dict_keys(['de', 'sk', 'hu']) is not JSON serializable
Instead, I use:
> abbrevs = python.get("list(capcities.keys())")
> abbrevs
[1] "sk" "de" "hu"