Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

R Interface to Python

License

NotificationsYou must be signed in to change notification settings

rstudio/reticulate

Repository files navigation

R-CMD-check

Thereticulate package provides a comprehensive set of tools forinteroperability between Python and R. The package includes facilitiesfor:

reticulated python

  • 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!

Getting started

Installation

Install thereticulate package from CRAN as follows:

install.packages("reticulate")

Python version

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.

Python packages

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.

Calling Python

There are a variety of ways to integrate Python code into your Rprojects:

  1. 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).

  2. Importing Python modules — Theimport() function enables you to import any Python module and callit’s functions directly from R.

  3. Sourcing Python scripts — Thesource_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).

  4. Python REPL — Therepl_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.

Python in R Markdown

Thereticulate package includes a Python engine forRMarkdown with the following features:

  1. Run Python chunks in a single Python session embedded within your Rsession (shared variables/state between Python chunks)

  2. Printing of Python output, including graphical output frommatplotlib.

  3. Access to objects created within Python chunks from R using thepyobject (e.g.py$x would access anx variable created withinPython from R).

  4. Access to objects created within R chunks from Python using therobject (e.g.r.x would access tox variable 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.

Importing Python modules

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.

Sourcing Python scripts

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.

Python REPL

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.

Type conversions

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:

RPythonExamples
Single-element atomic vectorScalar1,1L,TRUE,"foo"
Unnamed list or multi-element atomic vectorListc(1.0, 2.0, 3.0),c(1L, 2L, 3L)
Named listDictlist(a = 1L, b = 2.0),dict(x = x_data)
Matrix/ArrayNumPy ndarraymatrix(c(1,2,3,4), nrow = 2, ncol = 2)
Data FramePandas DataFramedata.frame(x = c(1,2,3), y = c("a", "b", "c"))
FunctionPython functionfunction(x) x + 1
NULL, TRUE, FALSENone, True, FalseNULL,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.

Learning more

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.

Why reticulate?

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.


[8]ページ先頭

©2009-2025 Movatter.jp