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:
py --list-paths
(windows)- FYI
python --list-paths
doesn’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 <- import("dotenv") dotenv <- import("google.generativeai") genai <- import("langchain_community") langchain_community
Via
source_python
Example
library(tidyverse) library(reticulate) source("funs.R") use_virtualenv("../../") source_python("funs.py") # stuff for (r in 1:nrow(res)) { cat(r, "\n") <- get_wikitext(res$film[r], res$year[r]) # r fun tmp_wikitext # skip if get_wikitext fails if (is.na(tmp_wikitext)) next if (length(tmp_wikitext) == 0) next # give the text to openai <- tryCatch( tmp_chat get_results(client, tmp_wikitext), # py fun error = \(x) NA ) # if openai returned a dict of 2 if (length(tmp_chat) == 2) { $writer[r] <- tmp_chat$writer res$producer[r] <- tmp_chat$producer res } }
get_results
is a python function defined infuns.py
RMarkdown
Also see Quarto >> R and Python
Basic set-up
--- title: "R Notebook" output: html_notebook --- ```{r} ::opts_chunk$set( knitrecho = TRUE, message = FALSE, warning = FALSE )``` ```{r} library(reticulate) ``` ```{python} import pandas as pd import numpy as np ```