Alumnus of Freie Universität Berlin – Michael Grünstäudl, PhD

Successful habilitation in botany and bioinformatics

Using rPython to call Python in R

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"

Der Beitrag wurde am Friday, den 16. December 2016 um 11:52 Uhr von Michael Grünstäudl veröffentlicht und wurde unter bioinformatics, teaching abgelegt. Sie können die Kommentare zu diesem Eintrag durch den RSS 2.0 Feed verfolgen. Sie können einen Kommentar schreiben, oder einen Trackback auf Ihrer Seite einrichten.

Leave a Reply

Captcha
Refresh
Hilfe
Hinweis / Hint
Das Captcha kann Kleinbuchstaben, Ziffern und die Sonderzeichzeichen »?!#%&« enthalten.
The captcha could contain lower case, numeric characters and special characters as »!#%&«.