reticulate

Misc

  • Reticulate-based R packages (Thread)

  • Before interactively running python in RStudio, start REPL

    reticulate::repl_python()

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_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")
      
        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_results is a python function defined in funs.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
    ```