reticulate
Misc
Reticulate-based R packages (Thread)
Before interactively running python in RStudio, start REPL
::repl_python() reticulate
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} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE ) ``` ```{r} library(reticulate) ``` ```{python} import pandas as pd import numpy as np ```