Advanced Usage Examples for rpy-bridge

This page demonstrates advanced usage of rpy-bridge, including:

  • Calling custom R functions

  • Handling multiple scripts

  • Base R functions and package functions

  • Python-to-R conversion and edge cases

  • Using functions returning lists or data frames

Note

Adjust paths to the R scripts as needed for your system. Make sure R and rpy2 are installed and accessible.

R Scripts used in this example

  • examples/toy_funcs.R

  • examples/toy_funcs_more.R

These scripts contain toy functions like add_and_scale, multiply_table, make_list_of_dfs, seq_vector, square_table, and make_named_list. You can find them in rpy-bridge examples directory on GitHub.

Python Example

 1"""
 2examples/advanced_usage.py
 3
 4Demonstrates advanced usage of RFunctionCaller.
 5- Multiple scripts
 6- Custom R functions
 7- Base R and package functions
 8- Python-to-R type conversion
 9- Handling edge cases and lists of DataFrames
10"""
11
12from pathlib import Path
13
14from rpy_bridge import RFunctionCaller
15
16# -----------------------------
17# Setup: paths to R scripts
18# -----------------------------
19scripts_dir = Path("./examples")  # directory containing toy_funcs.R
20script1 = scripts_dir / "toy_funcs.R"
21script2 = scripts_dir / "toy_funcs_more.R"  # optional second script
22
23# Initialize RFunctionCaller with multiple scripts and packages
24caller = RFunctionCaller(
25    path_to_renv=None,
26    scripts=[script1, script2],
27    packages=["dplyr"],  # ensure package is loaded
28)
29
30
31# -----------------------------
32# Call custom R functions
33# -----------------------------
34print("add_and_scale(2,3) →", caller.call("add_and_scale", 2, 3))
35print("add_and_scale(2,3, scale=5) →", caller.call("add_and_scale", 2, 3, scale=5))
36
37df = caller.call("multiply_table", 2, 5, times=4)
38print("multiply_table result:\n", df)
39
40# --- Call toy_funcs_more.R ---
41print(
42    "seq_vector(1,10, step=2, reverse=True) →",
43    caller.call("seq_vector", start=1, end=10, step=2, reverse=True),
44)
45print("square_table(5) →", caller.call("square_table", n=5))
46print("make_named_list() →", caller.call("make_named_list"))
47
48# -----------------------------
49# Base R functions
50# -----------------------------
51print("sum([1,2,3,4,5]) →", caller.call("sum", [1, 2, 3, 4, 5]))
52print("mean([1.0, 2.0, 3.0]) →", caller.call("mean", [1.0, 2.0, 3.0]))
53print("toupper(['hello','world']) →", caller.call("toupper", ["hello", "world"]))
54print("all([True,True,False]) →", caller.call("all", [True, True, False]))
55print("rep([1,2], times=3) →", caller.call("rep", [1, 2], times=3))
56
57# --- R objects ---
58print("c(1,2,3) → vector:", caller.call("c", 1, 2, 3))
59print(
60    "list(a=1, b='foo', c=c(1,2,3)) →", caller.call("list", a=1, b="foo", c=[1, 2, 3])
61)
62print(
63    "data.frame(x=[1,2,3], y=['a','b','c']) →",
64    caller.call("data.frame", x=[1, 2, 3], y=["a", "b", "c"]),
65)
66
67# --- Named/default arguments ---
68print(
69    "round([1.234, 5.678], digits=1) →", caller.call("round", [1.234, 5.678], digits=1)
70)
71
72# --- Edge cases ---
73print("sum([]) →", caller.call("sum", []))
74print("mixed type c(1,'a',True) →", caller.call("c", 1, "a", True))
75
76# --- Using dplyr ---
77df_pkg = caller.call("data.frame", x=[1, 2, 3])
78nrows = caller.call("nrow", df_pkg)
79print("dplyr::nrow(data.frame(x=1:3)) →", nrows)
80
81# --- Function returning list of DataFrames ---
82list_of_dfs = caller.call("make_list_of_dfs")
83print("List of DataFrames:", list_of_dfs)
84
85# --- Mixed Python list types ---
86df_mixed = caller.call("data.frame", x=[1, None, 3], y=["a", "b", None])
87print("DataFrame with NAs:", df_mixed)

Explanation

  • Multiple scripts: RFunctionCaller can load multiple R scripts at once. Functions are accessible via their namespaces.

  • Custom R functions: You can call your own R functions and pass Python objects directly.

  • Base R functions: Built-in R functions like sum, mean, toupper, etc., can be called directly from Python.

  • Package functions: Use package::function syntax to call functions from installed R packages, e.g., dplyr::n_distinct.

  • Data conversion: Python scalars, lists, and dictionaries are automatically converted to R vectors, lists, or data frames, and vice versa.

  • Edge cases: Handles empty vectors, mixed types, and missing values (Python None → R NULL).

Note

This example is intended to illustrate functionality. You may need to adjust paths to R scripts and ensure packages are installed in your R environment for execution.