Skip to content

benchling/R-Datasets-Example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

44 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sample Code - Working with Datasets Using R

A repository containing the sample scripts described in the Working with Datasets Using R developer guide.

Provided for educational purposes only; not for production use.

Quick Setup

  1. Install R 4.5.3+ (if not already installed)
  2. Install dependencies: Rscript -e "renv::restore()"
  3. Create Analysis: Create an analysis in Benchling
  4. Upload Sample Data: Attach examples/sample_ic50_data.csv as an input dataset to your analysis
  • Note: In production usage, this would be an existing dataset or results table from your experiments
  1. Get Analysis Key: In your analysis, click "Connect with external tool""Copy Analysis Key"
  2. Run the workflow: The script will prompt for your analysis key - that's it!

Authentication Methods

This repository uses Analysis Key (JWT) authentication by default.

Analysis Key Structure: ana_XXXXX:eyJhbGc... (analysis_id + JWT token separated by colon)

Analysis Key (JWT) - Default ✅

Best for: Learning, demos, workflows under 10 minutes

  • Simple: Just paste your analysis key
  • User-attributable: Actions are tied to the person who generated the key
  • ⚠️ Expires after 10 minutes: If your workflow takes longer, it will fail
  • ⚠️ Analysis-specific: Each analysis has its own key

The JWT token (part after the colon) contains the authentication credentials and is used directly as the bearer token for API requests.

Benchling App (OAuth2) - Alternative

Best for: Production systems, long-running workflows, processing multiple analyses

  • Permanent credentials: No expiration
  • Reusable: Works across all analyses
  • ⚠️ More setup: Requires creating a Benchling App
  • ⚠️ App-attributable: Actions are tied to the app, not a specific user

Want to use App credentials? Set USE_OAUTH2 <- TRUE at the top of get_dataframe.R (line 12) and/or app.R (line 17). See Benchling Apps Guide for setup.

📖 Detailed Setup Instructions (click to expand)

Prerequisites

  • R 4.5.3+ installed
  • Access to a Benchling tenant
  • Access to Benchling Analyses feature

Part 1: Create a Benchling Analysis

Analyses are where you'll attach input datasets and receive output results.

  1. Navigate to Analyses:
  • In Benchling, go to your project or notebook
  • Click "Create""Analysis"
  1. Configure Analysis:
  • Name: e.g., "IC50 Dose-Response Calculation"
  • Description: Optional, explains what this analysis does
  1. Attach Input Dataset:
  • Click "Add Input""Dataset"
  • For this example: Upload examples/sample_ic50_data.csv from this repository
  • For production use: Select an existing dataset or results table from your experiments
  • Required columns:
    • Cell.Mortality.Concentration - Drug concentration values
    • Cell.Mortality.Mortality.24h - Mortality percentage at 24 hours
    • Cell.Line.Name - Cell line identifier Example data format:
  1. Get the Analysis Key:
  • In your analysis, click "Connect with external tool"
  • In the popup window, click "Copy Analysis Key"
  • Format looks like: ana_XXXXXXXX:eyJhbGc... (analysis_id:JWT token)
  • Note: Analysis keys are specific to each analysis run and expire after 10 minutes

Part 2: Install Dependencies

# Restore the renv environment (installs all packages)
Rscript -e "renv::restore()"

# Or install packages individually
Rscript -e "renv::install(c('httr', 'jsonlite', 'base64enc', 'drc', 'plotly', 'htmlwidgets', 'pracma'))"

Note: On macOS, you may need CMake first:

brew install cmake

Part 3: Run the Workflow

⚠️ Important: Scripts must run sequentially in the same R session because results_analysis.R depends on variables from get_dataframe.R.

Option A: RStudio (Recommended)

source('get_dataframe.R')    # Will prompt: "Analysis Key: "
                             # Paste: ana_XXXXX:eyJhbGc...
ls()     # Verify: df, subdomain, analysis_id, access_token, folder_id
head(df) # Check data loaded correctly
source('results_analysis.R')

Option B: Script Based Execution in Interactive R Session

source('get_dataframe.R')
# Prompts for analysis key, paste it and press Enter
source('results_analysis.R')

Option C: Non-Interactive (Command Line)

export BENCHLING_ANALYSIS_KEY="ana_XXXXX:eyJhbGc..."
Rscript -e "source('get_dataframe.R'); source('results_analysis.R')"

Option D: Shiny Web App (Easiest) from Interactive R Session

shiny::runApp("app.R")
# Enter your analysis key in the web interface

Verify Success

The scripts print status codes as they run:

[1] "200"  # Dataframe upload successful
[1] "200"  # File upload successful
[1] "200"  # Analysis update successful

Check your Analysis in Benchling - you should see:

  • Dataset: Mortality_IC50 - CSV with IC50 statistics
  • File: mortality_24h.html - Interactive plot

Common Issues

Error: "HTTP 401 Unauthorized" or "Failed to authenticate"

  • Your analysis key JWT may have expired (check the exp field in the JWT)
  • Generate a new analysis key from your Benchling analysis
  • Ensure you copied the complete key (format: ana_XXXXX:eyJhbGc...)

Error: "HTTP 404 Not Found"

  • analysis_id is incorrect
  • Check the analysis ID in the Benchling URL
  • Ensure the analysis exists and you have access

Error: "Variables not found in results_analysis.R"

  • Must run get_dataframe.R first in the same R session
  • Don't start a new R session between running the scripts

Error: "Package not found"

  • Run renv::restore() to install all dependencies

Error: "No input dataframes found"

  • Ensure you've attached an input dataset to your analysis in Benchling
  • Dataset must have the required columns (see data format above)

Data Flow

┌─────────────────────────────────────────┐
│        Benchling Analysis               │
│  Input Dataset (CSV)                    │
└──────────────┬──────────────────────────┘
               │
               ▼
    ┌──────────────────┐
    │ get_dataframe.R  │
    │ 1. Authenticate  │
    │ 2. Fetch dataset │
    └────────┬─────────┘
             │
             ▼
    Variables: df, subdomain,
    analysis_id, access_token
             │
             ▼
    ┌──────────────────┐
    │ results_analysis │
    │ 1. Calculate IC50│
    │ 2. Generate plot │
    │ 3. Upload both   │
    └────────┬─────────┘
             │
             ▼
┌─────────────────────────────────────────┐
│        Benchling Analysis               │
│  Output: Mortality_IC50 (CSV)           │
│  Output: mortality_24h.html (plot)      │
└─────────────────────────────────────────┘

Additional Resources

Local Testing 🧪

Want to test IC50 calculations without connecting to Benchling? Use the local test script:

# From project root:
source("examples/local_test.R")

# Or from examples directory:
setwd("examples")
source("local_test.R")

What it does:

  • Loads dose-response data from examples/sample_ic50_data.csv (21 observations, 7 concentrations × 3 replicates)
  • Calculates IC50 using 4-parameter log-logistic model
  • Uses utility functions from utils.R
  • Creates interactive plotly visualization
  • Generates results summary

Output files:

  • examples/local_test_output.html - Interactive plot (open in browser)
  • examples/local_test_summary.csv - Results table

Prerequisites: None! Works completely offline with sample data. Perfect for testing during development.


Usage

Main Script Files

  • get_dataframe.R - Pulls input dataset from Benchling using analysis key
  • results_analysis.R - Performs IC50 calculation, creates plot, and uploads to Benchling
  • app.R - Full-featured Shiny web app with UI for IC50 analysis
  • utils.R - Shared utility functions for IC50 calculation and plotting

Full Workflow (Benchling Integration)

Option 1: Shiny Web App (Easiest)

shiny::runApp("app.R")  # Opens web interface

Option 2: Command Line Scripts

source('get_dataframe.R')     # Will prompt for analysis key
source('results_analysis.R')

⚠️ Important:

  • Scripts must run sequentially in the same R session
  • The script will prompt you for the analysis key
  • Analysis keys contain JWT tokens that may expire - regenerate if needed

Once you're confident with the workflow, these techniques can be applied to more robust applications using tools like Shiny.

About

Sample scripts demonstrating how to import/export datasets from Benchling using R

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages