Add Python Script in Rmd File
To use Python of a specified conda environment (instaed of the default one chosen by R) in a R markdown (*.Rmd) file, firstly install reticulate package. Then add 3 things into the setup seciton of the Rmd file:
-
Add 2 entries into R's
PATH
environment variable: the path ofconda
, and the path of the conda env; -
Load
reticulate
; -
Load the target conda env;
For example, I built a conda env named pandas023test
with full Anaconda packages,
in the folder /home/leo/apps/miniconda3/envs/pandas023test
.
Now the Python scripts can be added into a Rmd file:
$ cat example.Rmd
---
title: "Exercises for 2.2"
output: html_document
---
```{r setup, include=FALSE}
Sys.setenv(PATH=paste('/home/leo/apps/miniconda3/envs/pandas023test/bin:/home/leo/apps/miniconda3/bin', Sys.getenv('PATH'), sep = ':'))
library(reticulate)
use_condaenv(condaenv = 'pandas023test', conda = "/home/leo/apps/miniconda3/bin/conda", required = TRUE)
```
Some texts here.
```{python}
import pandas as pd
df = pd.DataFrame({'Animal' : ['Falcon', 'Falcon', 'Parrot', 'Parrot'],
'Max Speed' : [380., 370., 24., 26.]})
print(df)
grps = df.groupby(['Animal'])
print(grps)
print(grps.mean())
```
Note r setup
above is not r, setup
.
See another example with source code and rendered markdown file with calculation results.
Run Python REPL in R console
After run the codes in r setup
section above, start a Python REPL with
repl_python()
.
Verify the environment is loaded successfully with:
py_config()
py_discover_config()
Ref: