R and Python

side-note
Author

Josef Fruehwald

Inside a quarto notebook, you can actually go back and forth between R code chunks and Python code chunks, and even pass data between the two if you load the reticulate package.

r
names <- c("Ralph", "Rachel")
python
names = ["Paul", "Pamela"]

You can get Python data inside R with the py object.

r
py$names
[1] "Paul"   "Pamela"

And the R data in Python with the r object.

python
r.names
['Ralph', 'Rachel']

The set up is pretty good and interpreting data types from each language.

r
library(palmerpenguins)

df <- head(penguins)
python
r.df
  species     island  bill_length_mm  ...  body_mass_g     sex  year
0  Adelie  Torgersen            39.1  ...         3750    male  2007
1  Adelie  Torgersen            39.5  ...         3800  female  2007
2  Adelie  Torgersen            40.3  ...         3250  female  2007
3  Adelie  Torgersen             NaN  ...  -2147483648     NaN  2007
4  Adelie  Torgersen            36.7  ...         3450  female  2007
5  Adelie  Torgersen            39.3  ...         3650    male  2007

[6 rows x 8 columns]

You can even do wilder things like use python libraries inside of R

r
np <- reticulate::import("numpy", as = "np")
np$ones(10L)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

Reuse

CC-BY 4.0

Citation

BibTeX citation:
@online{fruehwald,
  author = {Fruehwald, Josef},
  title = {R and {Python}},
  url = {https://lin611-2024.github.io/notes/side-notes/content/reticulate.html},
  langid = {en}
}
For attribution, please cite this work as:
Fruehwald, Josef. n.d. “R and Python.” https://lin611-2024.github.io/notes/side-notes/content/reticulate.html.