Skip to content

Instantly share code, notes, and snippets.

@srgorelik
Last active May 13, 2019 18:02
Show Gist options
  • Save srgorelik/9edf4075e1efd77ccfc4a09f07de6764 to your computer and use it in GitHub Desktop.
Save srgorelik/9edf4075e1efd77ccfc4a09f07de6764 to your computer and use it in GitHub Desktop.
How to use the reticulate package to work with Python interactively in an R session.

This is a quick walthrough on how to use the reticulate package to work with Python interactively in an R session.

First, to specify the Python version to call (e.g., 3 instead of 2), set a RETICULATE_PYTHON path variable:

$ which python3
/usr/bin/python3
$ echo "RETICULATE_PYTHON='/usr/bin/python3'" >> ~/.Renviron

Note, the use_python('/usr/bin/python3') method described here does not seem to work, but the method described above seems to do the trick (source).

Second, start a fresh R session for the above path to take effect. Now, to run Python interactively inside of R:

> install.packages('reticulate')
> library(reticulate)
> repl_python()
Python 3.5.3 (/usr/bin/python3)
Reticulate 1.10 REPL -- A Python interpreter in R.
>>> import numpy as np
>>> arr = np.array([[0,1],[1,0]])
>>> arr
array([[0, 1],
       [1, 0]])
>>> exit
> print(py$arr)
     [,1] [,2]
[1,]    0    1
[2,]    1    0
> class(py$arr)
[1] "matrix"

Notice that the correct Python version was called. Also notice that variables created within the interactive Python session can be called from R after Python is exited.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment