- Notifications
You must be signed in to change notification settings - Fork345
rstudio/reticulate
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Thereticulate package provides a comprehensive set of tools forinteroperability between Python and R. The package includes facilitiesfor:
Calling Python from R in a variety of ways including R Markdown,sourcing Python scripts, importing Python modules, and using Pythoninteractively within an R session.
Translation between R and Python objects (for example, between R andPandas data frames, or between R matrices and NumPy arrays).
Flexible binding to different versions of Python including virtualenvironments and Conda environments.
Reticulate embeds a Python session within your R session, enablingseamless, high-performance interoperability. If you are an R developerthat uses Python for some of your work or a member of data science teamthat uses both languages, reticulate can dramatically streamline yourworkflow!
Install thereticulate package from CRAN as follows:
install.packages("reticulate")By default, reticulate uses an isolated python virtual environment named "r-reticulate".
Theuse_python() function enables you to specify an alternate python,for example:
library(reticulate)use_python("/usr/local/bin/python")
Theuse_virtualenv() anduse_condaenv() functions enable you tospecify versions of Python in virtual or Conda environments, forexample:
library(reticulate)use_virtualenv("myenv")
See the article onPython VersionConfigurationfor additional details.
You can install any required Python packages using standard shell toolslikepip andconda. Alternately, reticulate includes a set offunctions for managing and installing packages within virtualenvs andConda environments. See the article onInstalling PythonPackagesfor additional details.
There are a variety of ways to integrate Python code into your Rprojects:
Python in R Markdown — A new Pythonlanguage engine for R Markdown that supports bi-directionalcommunication between R and Python (R chunks can access Pythonobjects and vice-versa).
Importing Python modules — The
import()function enables you to import any Python module and callit’s functions directly from R.Sourcing Python scripts — The
source_python()function enables you to source a Python script thesame way you wouldsource()an R script (Python functions andobjects defined within the script become directly available to the Rsession).Python REPL — The
repl_python()function createsan interactive Python console within R. Objects you create withinPython are available to your R session (and vice-versa).
Each of these techniques is explained in more detail below.
Thereticulate package includes a Python engine forRMarkdown with the following features:
Run Python chunks in a single Python session embedded within your Rsession (shared variables/state between Python chunks)
Printing of Python output, including graphical output frommatplotlib.
Access to objects created within Python chunks from R using the
pyobject (e.g.py$xwould access anxvariable created withinPython from R).Access to objects created within R chunks from Python using the
robject (e.g.r.xwould access toxvariable created within Rfrom Python)
Built in conversion for many Python object types is provided, includingNumPy arrays andPandas data frames. For example, you canuse Pandas to read and manipulate data then easily plot the Pandas dataframe usingggplot2:
Note that the reticulate Python engine is enabled by default within RMarkdown whenever reticulate is installed.
See theR Markdown PythonEnginedocumentation for additional details.
You can use theimport() function to import any Python module and callit from R. For example, this code imports the Pythonos module andcalls thelistdir() function:
library(reticulate)os<- import("os")os$listdir(".")
[1] ".git" ".gitignore" ".Rbuildignore" ".RData" [5] ".Rhistory" ".Rproj.user" ".travis.yml" "appveyor.yml" [9] "DESCRIPTION" "docs" "external" "index.html"[13] "index.Rmd" "inst" "issues" "LICENSE"[17] "man" "NAMESPACE" "NEWS.md" "pkgdown"[21] "R" "README.md" "reticulate.Rproj" "src"[25] "tests" "vignettes"Functions and other data within Python modules and classes can beaccessed via the$ operator (analogous to the way you would interactwith an R list, environment, or reference class).
Imported Python modules support code completion and inline help:
SeeCalling Python fromRfor additional details on interacting with Python objects from within R.
You can source any Python script just as you would source an R scriptusing thesource_python() function. For example, if you had thefollowing Python scriptflights.py:
importpandasdefread_flights(file):flights=pandas.read_csv(file)flights=flights[flights['dest']=="ORD"]flights=flights[['carrier','dep_delay','arr_delay']]flights=flights.dropna()returnflights
Then you can source the script and call theread_flights() function asfollows:
source_python("flights.py")flights<- read_flights("flights.csv")library(ggplot2)ggplot(flights, aes(carrier,arr_delay))+ geom_point()+ geom_jitter()
See thesource_python() documentation for additional details onsourcing Python code.
If you want to work with Python interactively you can call therepl_python() function, which provides a Python REPL embedded withinyour R session. Objects created within the Python REPL can be accessedfrom R using thepy object exported from reticulate. For example:
Enterexit within the Python REPL to return to the R prompt.
Note that Python code can also access objects from within the R sessionusing ther object (e.g.r.flights). See therepl_python()documentation for additional details on using the embedded Python REPL.
When calling into Python, R data types are automatically converted totheir equivalent Python types. When values are returned from Python to Rthey are converted back to R types. Types are converted as follows:
| R | Python | Examples |
|---|---|---|
| Single-element atomic vector | Scalar | 1,1L,TRUE,"foo" |
| Unnamed list or multi-element atomic vector | List | c(1.0, 2.0, 3.0),c(1L, 2L, 3L) |
| Named list | Dict | list(a = 1L, b = 2.0),dict(x = x_data) |
| Matrix/Array | NumPy ndarray | matrix(c(1,2,3,4), nrow = 2, ncol = 2) |
| Data Frame | Pandas DataFrame | data.frame(x = c(1,2,3), y = c("a", "b", "c")) |
| Function | Python function | function(x) x + 1 |
| NULL, TRUE, FALSE | None, True, False | NULL,TRUE,FALSE |
If a Python object of a custom class is returned then an R reference tothat object is returned. You can call methods and access properties ofthe object just as if it was an instance of an R reference class.
The following articles cover the various aspects of usingreticulate:
Calling Python fromR— Describes the various ways to access Python objects from R as wellas functions available for more advanced interactions and conversionbehavior.
R Markdown PythonEngine— Provides details on using Python chunks within R Markdowndocuments, including how call Python code from R chunks andvice-versa.
Python VersionConfiguration— Describes facilities for determining which version of Python isused by reticulate within an R session.
Installing PythonPackages— Documentation on installing Python packages from PyPI or Conda,and managing package installations using virtualenvs and Condaenvironments.
Using reticulate in an RPackage— Guidelines and best practices for using reticulate in an Rpackage.
Arrays in R andPython —Advanced discussion of the differences between arrays in R andPython and the implications for conversion and interoperability.
PythonPrimer— Introduction to Python for R users.
From theWikipediaarticle on the reticulated python:
The reticulated python is a species of python found in Southeast Asia.They are the world’s longest snakes and longest reptiles…The specificname, reticulatus, is Latin meaning “net-like”, or reticulated, and isa reference to the complex colour pattern.
From theMerriam-Websterdefinition of reticulate:
1: resembling a net or network; especially : having veins, fibers, orlines crossing a reticulate leaf. 2: being or involving evolutionarychange dependent on genetic recombination involving diverseinterbreeding populations.
The package enables you toreticulate Python code into R, creating anew breed of project that weaves together the two languages.
About
R Interface to Python
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.



