Use Python & R With Reticulate
Use Python & R With Reticulate
The reticulate package lets you use Python and R together seamlessly in R code, in R Markdown documents, and in the RStudio IDE.
Reticulate provides automatic built-in conversion dict(..., convert = FALSE) Create a Python dictionary py_capture_output(expr, type = c("stdout", RUN PYTHON CODE
between Python and R for many Python types. object. Also py_dict to make a dictionary that uses "stderr")) Capture and return Python output. Also
Python objects as keys. dict(foo = "bar", index = 42L) py_suppress_warnings. py_capture_output("x") Execute Python code into the main Python
R Python module with py_run_file() or py_run_string().
Single-element vector Scalar np_array(data, dtype = NULL, order = "C") Create py_get_attr(x, name, silent = FALSE) Get an
Multi-element vector List NumPy arrays. np_array(c(1:8), dtype = "float16") attribute of a Python object. Also py_set_attr, • py_run_string(code, local = FALSE,
py_has_attr, and py_list_attributes. py_get_attr(x) convert = TRUE) Run Python code
List of multiple types Tuple array_reshape(x, dim, order = c("C", "F")) Reshape (passed as a string) in the main
Named list Dict a Python array. x <- 1:4; array_reshape(x, c(2, 2)) module. py_run_string("x = 10"); py$x
py_help(object) Open the documentation
Matrix/Array NumPy ndarray page for a Python object. py_help(sns)
py_func(object) Wrap an R function in a Python • py_run_file(file, local = FALSE, convert =
Data Frame Pandas DataFrame
function with the same signature. py_func(xor) TRUE) Run Python file in the main
Function Python function py_last_error() Get the last Python module. py_run_file("script.py")
NULL, TRUE, FALSE None, True, False py_main_thread_func(object) Create a function error encountered. Also py_clear_last_error
that will always be called on the main thread. to clear the last error. py_last_error() • py_eval(code, convert = TRUE) Run
Or, if you like, you can convert manually with a Python expression, return the result.
py_to_r(x) Convert a Python object to iterate(..., convert = FALSE) Apply an R function to py_save_object(object, filename, pickle = "pickle") Also py_call. py_eval("1 + 1")
an R object. Also r_to_py. py_to_r(x) each value of a Python iterator or return the values Save and load Python objects with pickle. Also
as an R vector, draining the iterator as you go. Also py_load_object. py_save_object(x, "x.pickle") Access the results, and anything else in Python's
tuple(..., convert = FALSE) Create a iter_next and as_iterator. iterate(iter, print) main module, with py.
Python tuple. tuple("a", "b", "c") with(data, expr, as = NULL, ...) Evaluate an
py_iterator(fn, completed = NULL) Create a Python expression within a Python context manager. • py An R object that contains
iterator from an R function. seq_gen <- function(x){n py <- import_builtins(); with(py$open("output.txt", the Python main module and
<- x; function() {n <<- n + 1; n}};py_iterator(seq_gen(9)) "w") %as% file, { file$write("Hello, there!")}) the results stored there. py$x
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at rstudio.github.io/reticulate/ • reticulate 1.12.0 • Updated: 2019-04
Python in the IDE Requires reticulate plus RStudio v1.2 or higher. Configure Python
Syntax Tab completion for Python Source Execute Python Press F1 over a matplotlib Reticulate binds to a local instance of Python when you first call import() directly
highlighting for functions and objects (and Python code line by line Python symbol plots display or implicitly from an R session. To control the process, find or build your desired
Python scripts Python modules imported scripts. with Cmd + Enter to display the in plots pane. Python instance. Then suggest your instance to reticulate. Restart R to unbind.
and chunks in R scripts) (Ctrl + Enter) help topic for
Find Python
that symbol.
A REPL (Read, Eval, Print Loop) is a command • virtualenv_install(envname, packages, • use_virtualenv(virtualenv = NULL,
line where you can run Python code and view ignore_installed = FALSE) Install a package required = FALSE) Suggest a Python
the results. within a virtualenv. virtualenv_install( virtualenv. use_virtualenv("~/myenv")
"r-pandas", packages = "pandas")
1. Open in the console with repl_python(), • use_condaenv(condaenv = NULL,
or by running code in a Python script with • virtualenv_remove(envname, packages = conda = "auto", required = FALSE)
Cmd + Enter (Ctrl + Enter) . NULL, confirm = interactive()) Remove Suggest a Conda env to use.
individual packages or an entire virtualenv. use_condaenv(condaenv = "r-nlp",
• repl_python(module = NULL, quiet = virtualenv_remove("r-pandas", packages = conda = "/opt/anaconda3/bin/conda")
getOption("reticulate.repl.quiet", "pandas")
default = FALSE)) Launch a Python 3. Within virtualenvs and conda envs that carry
REPL. Run exit to close. repl_python() • conda_install(envname, packages, forge = the same name as the imported module.
TRUE, pip = FALSE, pip_ignore_installed = e.g. ~/anaconda/envs/nltk for import("nltk")
2. Type commands at >>> prompt TRUE, conda = "auto") Install a package
within a Conda env. conda_install(
3. Press Enter to run code "r-pandas", packages = "plotly") 4. At the location of the Python binary
discovered on the system PATH
4. Type exit to close and return to R console • conda_remove(envname, packages = NULL, (i.e. Sys.which("python"))
conda = "auto") Remove individual packages
or an entire Conda env. conda_remove( 5. At customary locations for Python, e.g./usr/
"r-pandas", packages = "plotly") local/bin/python, /opt/local/bin/python...
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at rstudio.github.io/reticulate/ • reticulate 1.12.0 • Updated: 2019-04