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)
A data.frame: 6 × 10
Unnamed: 0rawidroivolumeminmaxmeanstdtypelevel
<dbl><chr><chr><dbl><dbl><dbl><dbl><dbl><dbl><dbl>
11kirby127a_3_1_ax.imgTelencephalon_L531111 0374128.301351.859311
22kirby127a_3_1_ax.imgTelencephalon_R543404 0300135.068353.647111
33kirby127a_3_1_ax.imgDiencephalon_L 968315295193.548832.273311
44kirby127a_3_1_ax.imgDiencephalon_R 967810335193.705132.786911
55kirby127a_3_1_ax.imgMesencephalon 1026855307230.858329.224911
66kirby127a_3_1_ax.imgMetencephalon 159402 2299138.520052.224111

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))
  1. 0.483189688515033
  2. 1.15551860776896
  3. -0.230891758864093
  4. 0.349830581235137
  5. -2.15526446076882

(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.