Using rpy-bridge with renv Projects

Python Example

 1"""
 2examples/renv_usage.py
 3
 4Demonstrates rpy-bridge usage with a project-specific renv environment.
 5"""
 6
 7from pathlib import Path
 8
 9from rpy_bridge import RFunctionCaller
10
11# ----------------------------------------
12# Example 1: Activate a renv Project
13# ----------------------------------------
14
15# Point to the root of your R project (containing renv/)
16project_dir = Path("/path/to/my_r_project")  # or Path("/path/to/my_r_project/renv")
17script_path = project_dir / "scripts" / "my_script.R"
18
19# Initialize RFunctionCaller with renv
20rfc = RFunctionCaller(path_to_renv=project_dir, scripts=script_path)
21
22# Call a function from the script
23result = rfc.call("add_numbers", 10, 5)
24print("add_numbers(10,5) =", result)
25
26
27# ----------------------------------------
28# Example 2: Call Installed Packages within renv
29# ----------------------------------------
30
31# Call 'mean' from base R
32mean_val = rfc.call("base::mean", [1, 2, 3, 4])
33print("mean([1,2,3,4]) =", mean_val)
34
35# Call a function from a package installed in renv, e.g., dplyr::n_distinct
36n_unique = rfc.call("dplyr::n_distinct", [1, 2, 2, 3, 3, 3])
37print("dplyr::n_distinct([1,2,2,3,3,3]) =", n_unique)

Note

You can also point path_to_renv directly to the renv folder: project_dir = Path(“/path/to/my_r_project/renv”).