Skip to main content

A lightweight Python plugin to execute R scripts and retrieve workspace variables

Project description

run-r

A lightweight partially vibecoded Python module to execute R scripts (with optional inputs) and retrieve all workspace variables. I wanted to avoid rpy2 as installing it on my machine led to a compatibility/dependency nightmare.

Features

  • Simple Interface: Execute R scripts with a single function call
  • Workspace Extraction: Automatically captures all variables from the R global environment
  • Bidirectional Data Transfer: Pass Python data to R and get results back
  • Type Handling: Handles various R data types (vectors, data frames, matrices, lists, S4 objects)
  • No Heavy Dependencies: Uses only standard library - no need for rpy2
  • Cross-Platform: Works on Windows, Linux, and macOS
  • Statistical Models: Full support for complex R objects like lme4 mixed-effects models

Requirements

  • Python 3.7+
  • R installation (the plugin will auto-detect R on Windows)
  • R package jsonlite (will be automatically installed if missing)

Installation

pip install run-r

Quick Start

Basic Usage

from run_r import run_r_script

# Run an R script and get all workspace variables
variables = run_r_script("my_script.R")

# Access variables
print(variables['my_variable'])
print(variables['my_dataframe'])

Pass Data from Python to R

import pandas as pd
from run_r import run_r_script

# Create a pandas DataFrame
df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [2, 4, 6, 8, 10]
})

# Pass it to R along with other parameters
result = run_r_script(
    "analysis.R",
    input_data={
        "data": df,
        "threshold": 5,
        "method": "linear"
    }
)

print(result['model_summary'])

Work with Statistical Models

import numpy as np
import pandas as pd
from run_r import run_r_script

# Generate sample data
df = pd.DataFrame({
    'subject_id': np.repeat(range(20), 30),
    'predictor': np.random.randn(600),
    'response': np.random.binomial(1, 0.5, 600)
})

# Fit a mixed-effects model in R
result = run_r_script(
    "fit_glmer.R",
    input_data={"study_data": df}
)

# Access model results
print(result['model']['fixed_effects'])
print(result['model']['fit_stats'])

Supported Data Types

Python to R

  • Basic types: int, float, str, bool, list, dict
  • NumPy arrays: Converted to R vectors/matrices
  • Pandas DataFrames: Converted to R data.frames
  • Pandas Series: Converted to R vectors

R to Python

  • Scalars: Numbers, strings, booleans
  • Vectors: Numeric, character, logical vectors
  • Data Frames: Converted to dictionaries of lists
  • Lists: Nested R lists
  • Matrices: Stored with dimension information
  • S4 Objects: Complex objects like lme4 models with full metadata
  • Functions/Environments: Captured as string representations

Command Line Usage

run-r path/to/script.R

Or using Python:

python -m run_r path/to/script.R

Advanced Usage

Custom R Executable

from run_r import RScriptRunner

runner = RScriptRunner(r_executable="/custom/path/to/Rscript")
variables = runner.run_script("analysis.R")

Control Output Verbosity

# Suppress R output
variables = run_r_script("script.R", verbose=False)

# Enable debug mode (keeps temporary files)
runner = RScriptRunner()
variables = runner.run_script("script.R", debug=True)

Reusable Runner Instance

from run_r import RScriptRunner

# Create runner once
runner = RScriptRunner()

# Run multiple scripts
result1 = runner.run_script("script1.R")
result2 = runner.run_script("script2.R", input_data={"x": 10})
result3 = runner.run_script("script3.R", verbose=False)

Examples

Example 1: Basic R Script

my_script.R:

x <- 1:10
y <- x^2
result <- sum(y)

Python:

from run_r import run_r_script

vars = run_r_script("my_script.R")
print(vars['x'])      # [1, 2, 3, ..., 10]
print(vars['y'])      # [1, 4, 9, ..., 100]
print(vars['result']) # 385

Example 2: Pass DataFrame to R

analysis.R:

# Input data is automatically loaded
model <- lm(y ~ x, data = df)
predictions <- predict(model)
r_squared <- summary(model)$r.squared

Python:

import pandas as pd
from run_r import run_r_script

df = pd.DataFrame({'x': [1, 2, 3, 4], 'y': [2, 4, 6, 8]})
result = run_r_script("analysis.R", input_data={"df": df})

print(result['predictions'])
print(result['r_squared'])

Example 3: Mixed-Effects Model

fit_model.R:

library(lme4)

# Fit generalized linear mixed-effects model
model <- glmer(
    response ~ predictor + (1|subject_id),
    data = study_data,
    family = binomial()
)

Python:

import pandas as pd
import numpy as np
from run_r import run_r_script

# Generate sample data
np.random.seed(42)
df = pd.DataFrame({
    'subject_id': np.repeat(range(20), 30),
    'predictor': np.random.randn(600),
    'response': np.random.binomial(1, 0.5, 600)
})

# Fit model in R
result = run_r_script("fit_model.R", input_data={"study_data": df})

# Access extracted model components
model = result['model']
print("Fixed effects:")
print(model['fixed_effects'])
print("\nModel fit:")
print(f"AIC: {model['fit_stats']['AIC']}")
print(f"BIC: {model['fit_stats']['BIC']}")

How It Works

  1. Script Execution: The plugin sources your R script in a fresh R environment
  2. Data Transfer: Input data is serialized to JSON and loaded into R
  3. Variable Capture: After execution, all objects are collected from the global environment
  4. Serialization: Variables are converted to JSON-compatible format using R's jsonlite
  5. Return: Variables are returned as a Python dictionary

Error Handling

try:
    variables = run_r_script("script.R")
except FileNotFoundError as e:
    print(f"Script not found: {e}")
except RuntimeError as e:
    print(f"R execution error: {e}")

Design Philosophy

This plugin uses a subprocess-based approach rather than rpy2 for several reasons:

  1. Lightweight: No heavy dependencies or compiled extensions
  2. Isolation: Each script runs in a clean R process
  3. Simplicity: Easy to understand and modify
  4. Portability: Works anywhere R is installed
  5. Auto-detection: Automatically finds R on Windows in common installation locations

Platform Notes

Windows

  • Automatically searches for R in common Windows locations
  • jsonlite package auto-installed on first run if missing

Linux/macOS

Building and Publishing

To build the package:

cd package
python -m build

To install locally for testing:

pip install -e .

To upload to PyPI:

python -m twine upload dist/*

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

run_r-0.2.5.tar.gz (19.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

run_r-0.2.5-py3-none-any.whl (12.2 kB view details)

Uploaded Python 3

File details

Details for the file run_r-0.2.5.tar.gz.

File metadata

  • Download URL: run_r-0.2.5.tar.gz
  • Upload date:
  • Size: 19.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for run_r-0.2.5.tar.gz
Algorithm Hash digest
SHA256 a43e2bc4b0435f27ed2e738520495e364d7084a9666175d651fb7e4964e57e76
MD5 12b6e7dcda47800ca40afa7e8a27c4a5
BLAKE2b-256 aa7dc8bd4b0d3eeafe5585584fe075ddee86481d5fbed96d888d859cca3de321

See more details on using hashes here.

File details

Details for the file run_r-0.2.5-py3-none-any.whl.

File metadata

  • Download URL: run_r-0.2.5-py3-none-any.whl
  • Upload date:
  • Size: 12.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for run_r-0.2.5-py3-none-any.whl
Algorithm Hash digest
SHA256 a4f607056d223ead3162bb3dbedef27040a9938218468a167bb6df643136f342
MD5 dcd17513e57eccef8d25d209e4bbc182
BLAKE2b-256 9a7a65eb98a4450a39a3cc386c8f1f70db25d682ee17d9452a60acd466553950

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page