DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Using Python in R Environment


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:

  1. Add 2 entries into R's PATH environment variable: the path of conda, and the path of the conda env;

  2. Load reticulate;

  3. 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:

  • reticulate: R interface to Python

  • R Markdown Python Engine

  • From Jupyter Notebooks to R Markdown

  • Importing matplotlib with reticulate in R



Published

Jun 21, 2018

Last Updated

Apr 23, 2019

Category

Tech

Tags

  • python 136
  • rlang 17
  • rstudio 5

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor