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.