reticulate
Misc
- {reticulate}, {rpy2}
- Reticulate-based R packages (Thread)
- Before interactively running python in RStudio, start REPL:
reticulate::repl_python() - Get current python versions installed:
uv python list- Lists versions available for download and install and the paths of those already installed on your computer
py --list-paths(windows 10)- FYI
python --list-pathsdoesn’t work
- FYI
- Avoid conversion whenever possible. Achieved by using the
import(<library>, convert = FALSE)- When converting objects between R and Python, a new copy of the object is created in the target language. This slows down execution and increases memory use.
- Useful when working with large objects in Python that do not require manipulation in R
Python in R Scripts
Create Virtual Environment, Install Libraries, Activate VE, Import Modules (source)
library(reticulate) # Step 1: Create a virtual environment virtualenv_create(envname = "gemini") ## Step 1.1: Install the appropriate modules py_install( c("google-generativeai", "langchain", "langchain-community", "pypdf", "python-dotenv"), pip = T, virtualenv = "gemini" ) # Step 2: Use the virtual environment use_virtualenv("gemini") # Step 3: Import installed modules dotenv <- import("dotenv") genai <- import("google.generativeai") langchain_community <- import("langchain_community")Via
source_pythonExample
library(tidyverse) library(reticulate) source("funs.R") use_virtualenv("../../") source_python("funs.py") # stuff for (r in 1:nrow(res)) { cat(r, "\n") tmp_wikitext <- get_wikitext(res$film[r], res$year[r]) # r fun # skip if get_wikitext fails if (is.na(tmp_wikitext)) next if (length(tmp_wikitext) == 0) next # give the text to openai tmp_chat <- tryCatch( get_results(client, tmp_wikitext), # py fun error = \(x) NA ) # if openai returned a dict of 2 if (length(tmp_chat) == 2) { res$writer[r] <- tmp_chat$writer res$producer[r] <- tmp_chat$producer } }get_resultsis a python function defined infuns.py
RMarkdown
Also see Quarto >> R and Python
Basic set-up
--- title: "R Notebook" output: html_notebook --- ```{r} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE ) ``` ```{r} library(reticulate) ``` ```{python} import pandas as pd import numpy as np ```