Ch. 3 Sharing data objects
Last update: Thu Nov 19 17:20:43 2020 -0600 (49b93b1)
One of the advantages of running R and Python code chunks in the same document is that we can share object and variables between the environment of both programming languages. There are functions at what R excels, and functions that run better at Python. We take the best of both worlds.
We can share object from R in Python, or share Python objects in R.
3.1 From R to Python, back to R
- Always load the Python environment with the packages you need.
R
library(reticulate)
use_condaenv("r-python")
- Load the dataset in R and assign it to an R object. Let’s call it
autos
:
R
# R chunk
autos = cars # assign cars to autos
- Read the R object from Python by adding the prefix
r.
before the name of the R objectautos
. Then, assign it to a Python object that we will nameautos_py
.
- Make a calculation between two columns in the dataset (distance and speed), and assign it to a new column in the dataset with
autos_py['time']
.
Python
- From R, read the Python object
py$autos_py
and plot the dataset with the new columntime
, that you obtained in Python. Observe that we added the prefixpy$
in front of the Python objectautos_py
:
R
# R chunk
plot(py$autos_py) # plot a Python data object