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)
Unnamed: 0 | rawid | roi | volume | min | max | mean | std | type | level | |
---|---|---|---|---|---|---|---|---|---|---|
<dbl> | <chr> | <chr> | <dbl> | <dbl> | <dbl> | <dbl> | <dbl> | <dbl> | <dbl> | |
1 | 1 | kirby127a_3_1_ax.img | Telencephalon_L | 531111 | 0 | 374 | 128.3013 | 51.8593 | 1 | 1 |
2 | 2 | kirby127a_3_1_ax.img | Telencephalon_R | 543404 | 0 | 300 | 135.0683 | 53.6471 | 1 | 1 |
3 | 3 | kirby127a_3_1_ax.img | Diencephalon_L | 9683 | 15 | 295 | 193.5488 | 32.2733 | 1 | 1 |
4 | 4 | kirby127a_3_1_ax.img | Diencephalon_R | 9678 | 10 | 335 | 193.7051 | 32.7869 | 1 | 1 |
5 | 5 | kirby127a_3_1_ax.img | Mesencephalon | 10268 | 55 | 307 | 230.8583 | 29.2249 | 1 | 1 |
6 | 6 | kirby127a_3_1_ax.img | Metencephalon | 159402 | 2 | 299 | 138.5200 | 52.2241 | 1 | 1 |
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))
- 0.483189688515033
- 1.15551860776896
- -0.230891758864093
- 0.349830581235137
- -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.