Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Python from R

Open In Colab

Python from R

R has an advanced python API called reticulate. If you primarily work in R and Rstudio, here is an RMD document that outlines calling python from R in RMD documents.

Here we’ll more focus on direct use of the reticulate API. You can install reticulate with install.packages("reticulate"). Or, in conda you can do conda install r-reticulate. Do that first.

library(reticulate)
pd = import("pandas")
url = "https://raw.githubusercontent.com/bcaffo/ds4bme_intro/master/data/kirby127a_3_1_ax_283Labels_M2_corrected_stats.csv"
dat = pd$read_csv(url)
head(dat)
Loading...

Python functions can be used as R functions. Here’s a simple example.

npr = import("numpy.random")
normalGenerator = npr$normal
normalGenerator(size=as.integer(5))
Loading...

(Of course, this example isn’t necessary since R already has rnorm.) Notice that you actually have to do the type conversion, as.integer, since python is more strongly typed than R.

In addition, you can have python code blocks within RMD blocks. In addition, you can call python scripts

In general, it’s only worth doing this if you mostly work in R and there’s a python function that you really need. Similarly, for calling R from within python.