
Rstudio Research Agent
- 1 installs
- Updated February 26, 2026
- jackkuo666/rstudio-research-agent
Scaffolds R research projects, runs R and RMarkdown analyses, resolves package dependencies, and generates publication-quality plots via ggplot2 with renv reproducibility.
About
Automates R and RStudio research workflows including project scaffolding, script execution, dependency debugging, and figure generation. A researcher or data scientist uses it to set up reproducible R projects and produce statistical reports or visualizations.
- Scaffolds standard R project structure with renv package locking
- Generates publication-quality ggplot2 figures with journal formatting
Rstudio Research Agent by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,803 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/jackkuo666/rstudio-research-agent --skill rstudio-research-agentAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| Last updated | February 26, 2026 |
| Repository | jackkuo666/rstudio-research-agent ↗ |
What it does
Scaffolds R research projects, runs R and RMarkdown analyses, resolves package dependencies, and generates publication-quality plots via ggplot2 with renv reproducibility.
Files
RStudio Research Agent
A Claude Code skill for comprehensive R-based research workflow automation. This skill enables interaction with R and RStudio environments for scientific computing, statistical analysis, bioinformatics, and data visualization.
Overview
This skill helps researchers and data scientists:
- Create structured, reproducible R research projects
- Execute R scripts and RMarkdown analyses
- Debug environment and dependency issues
- Generate publication-quality plots and reports
- Manage R packages with renv for reproducibility
Use this skill when the user wants to:
- Create a new R project with standard structure
- Run R analyses on existing projects
- Troubleshoot R package dependencies
- Generate statistical reports or visualizations
- Set up reproducible R workflows
---
What This Skill Does
When activated, this skill provides four main capabilities:
1. Create R Research Projects
- Scaffold new R projects with standard folder structure
- Initialize Git repositories (optional)
- Set up
renvfor package management - Generate template scripts and reports
- Create
.Rprojfiles for RStudio
2. Run Analyses in Existing Projects
- Execute R scripts and RMarkdown files
- Handle parameterized analyses
- Return results, tables, and plots
- Generate HTML/PDF reports
3. Debug Environment and Dependencies
- Check for missing R packages
- Resolve library conflicts
- Suggest fixes for environment issues
- Verify R version compatibility
4. Generate Publication-Quality Plots
- Create figures with ggplot2 and other visualization libraries
- Export to PDF/PNG/SVG/TIFF formats
- Follow journal-specific formatting guidelines
- Support multi-panel composite figures
- Use color-blind friendly palettes
---
Example User Requests That Should Trigger This Skill
- "Create a new R project for my genomics data analysis"
- "Run
analysis.Rin my existing project and show results" - "Check if all required packages are installed"
- "Generate a scatter plot with regression line from my dataset"
- "Set up a reproducible R workflow for RNA-seq analysis"
- "Debug my R environment - packages won't load"
- "Create a statistical report for this clinical trial data"
---
Project Structure
Projects created by this skill follow this standardized structure:
my-research-project/
├── data/
│ ├── raw/ # Original, immutable data files
│ └── processed/ # Cleaned, transformed data
├── scripts/ # Analysis and processing scripts
├── results/
│ ├── figures/ # Plots and visualizations
│ ├── tables/ # Summary tables
│ └── models/ # Saved model objects (.rds files)
├── reports/ # R Markdown/Quarto documents
├── renv.lock # Package version lock file
├── .Rproj # RStudio project file
└── README.md # Project documentation---
Tools & Packages Commonly Used
| Purpose | R Packages |
|---|---|
| Data wrangling | tidyverse, data.table |
| Visualization | ggplot2, patchwork, scales |
| Statistics | stats, lme4, survival, broom |
| Bioinformatics | Bioconductor (DESeq2, edgeR, limma) |
| Reporting | rmarkdown, quarto |
| Reproducibility | renv |
---
Example Workflows
Creating a New Project
User: Create a new R project for gene expression analysis with Git initialized.
Skill actions: 1. Create directory structure (data/, scripts/, results/, reports/) 2. Initialize Git repository 3. Set up renv environment 4. Install DESeq2, tidyverse, ggplot2 5. Generate analysis template scripts 6. Create R Markdown report template
Running an Analysis
User: Run the differential expression analysis and return results.
Skill actions: 1. Activate project environment (renv) 2. Execute analysis script 3. Capture console output and plots 4. Return summary tables and model statistics 5. Generate report if requested
Debugging Dependencies
User: My R script fails with "package not found" errors.
Skill actions: 1. Check R version and package library paths 2. Scan script for required packages 3. Compare with installed packages 4. Generate installation commands 5. Check for version conflicts
---
Notes
- Requires R >= 4.0.0
- Supports both RStudio and command-line R
- Uses
renvfor reproducible package management - All outputs saved to files (not just console)
- Follows R best practices and modern conventions
---
Sub-Skills
This skill includes specialized sub-skills:
- create-project: Scaffold new R research projects
- run-analysis: Execute R scripts and generate reports
- debug-env: Troubleshoot R environments and dependencies
- generate-plots: Create publication-quality figures with journal formatting
Each sub-skill can be invoked independently or as part of a complete workflow.
# R specific
.Rhistory
.RData
.Rproj.user
# renv
renv/library/
renv/staging/
# User-specific settings
.claude/settings.local.json
RStudio Research Agent
A Claude Code skill for comprehensive R-based research workflow automation. This skill enables Claude to interact with R and RStudio environments for scientific research tasks.
Features
- Create R Research Projects - Scaffold new R projects with standard folder structure, Git initialization, and
renvpackage management - Run Analyses - Execute R scripts, RMarkdown, and Quarto documents with full output capture
- Debug Environment - Check for missing packages, resolve conflicts, and verify R version compatibility
- Generate Publication-Quality Plots - Create professional figures with journal-specific formatting guidelines
- Generate Reports - Create professional reports using RMarkdown and Quarto
Quick Start
Invoke the skill by asking Claude to work with R:
Create a new R project for gene expression analysisRun the analysis script in my R project and show resultsCheck if all required R packages are installedGenerate a volcano plot with Nature journal formattingCreate a scatter plot from my dataset and export as PDFProject Structure
Projects created by this skill follow standardized structure:
my-research-project/
├── data/
│ ├── raw/ # Original, immutable data files
│ └── processed/ # Cleaned, transformed data
├── scripts/ # Analysis and processing scripts
├── results/
│ ├── figures/ # Plots and visualizations
│ ├── tables/ # Summary tables
│ └── models/ # Saved model objects (.rds files)
├── reports/ # R Markdown/Quarto documents
├── renv.lock # Package version lock file
├── .Rproj # RStudio project file
└── README.md # Project documentationSub-Skills
create-project
Scaffold new R research projects with:
- Standard directory structure
- Git initialization (optional)
renvpackage management- Template scripts and reports
- RStudio project file
run-analysis
Execute R analyses with:
- Script execution and output capture
- RMarkdown/Quarto rendering
- Parameterized analysis support
- Results and plot tracking
debug-env
Troubleshoot R environments:
- Missing package detection
- Dependency resolution
- Version conflict diagnosis
- Installation command generation
generate-plots
Create publication-quality figures with:
- Scatter, bar, box, volcano, heatmap plots
- Journal-specific formatting (Nature, Science, PLOS ONE, IEEE)
- Export to PDF/PNG/SVG/TIFF formats
- Multi-panel composite figures
- Color-blind friendly palettes
Supported Analyses
| Type | Packages |
|---|---|
| Data wrangling | tidyverse, data.table |
| Visualization | ggplot2, patchwork, scales |
| Statistics | stats, lme4, survival, broom |
| Bioinformatics | Bioconductor (DESeq2, edgeR, limma) |
| Reporting | rmarkdown, quarto |
| Reproducibility | renv |
Requirements
- R >= 4.0.0
renvpackage:install.packages("renv")- (Optional) RStudio for
.Rprojsupport - (Optional) Quarto CLI for advanced reports
Templates Included
| Template | Description |
|---|---|
project_template.R | Complete project initialization script |
analysis.R | Standard analysis script template |
report.qmd | Quarto report template |
renv.lock.example | Example package lock file |
plot_functions.R | Publication-quality plotting functions library |
plot_examples.R | Example plots (scatter, bar, volcano, heatmap, etc.) |
Usage Examples
Create a New Project
Create an R project for RNA-seq differential expression analysis with GitRun Analysis
Run scripts/deseq2_analysis.R and return the summary tableDebug Environment
My script fails with "package not found" - check what's missingGenerate Report
Render the Quarto report to PDF with all figuresGenerate Publication Plots
Create a volcano plot with Nature journal formattingGenerate a scatter plot with regression line and export as PDFMake a multi-panel figure combining PCA and heatmapBest Practices
1. Never modify raw data - Always work on copies in data/processed/ 2. Use `renv::snapshot()` after installing new packages 3. Script everything - Avoid interactive-only analysis 4. Save all outputs - Plots, tables, and model objects 5. Document with reports - Use Quarto/R Markdown for reproducibility
License
MIT
Contributing
Suggestions and improvements welcome! This skill is designed to be a template for reproducible R research workflows.
# ============================================================================
# Analysis Script Template
# ============================================================================
# Description: [Brief description of what this analysis does]
# Author: [Your name]
# Date: [Date]
# Input: data/raw/[input_file]
# Output: results/[output_files]
# ============================================================================
# Load libraries --------------------------------------------------------------
library(tidyverse)
library(here)
# Set options -----------------------------------------------------------------
options(scipen = 999) # Disable scientific notation
# Define paths ----------------------------------------------------------------
DATA_RAW <- here("data/raw")
DATA_PROCESSED <- here("data/processed")
RESULTS_FIGURES <- here("results/figures")
RESULTS_TABLES <- here("results/tables")
RESULTS_MODELS <- here("results/models")
# Load data -------------------------------------------------------------------
# df <- read_csv(file.path(DATA_RAW, "filename.csv"))
# Data preparation ------------------------------------------------------------
# Clean and transform data here
# Analysis --------------------------------------------------------------------
# Perform your analysis here
# Visualization ---------------------------------------------------------------
# Create plots with ggplot2
# Save results ----------------------------------------------------------------
# ggsave(file.path(RESULTS_FIGURES, "figure1.png"), ...)
# Session info (for reproducibility) -----------------------------------------
sessionInfo()
# ============================================================================
# Publication-Quality Plot Examples
# ============================================================================
# Description: Example scripts demonstrating common publication plots
# Author: [Your name]
# Date: [Date]
# ============================================================================
library(ggplot2)
library(dplyr)
library(patchwork)
# Source the plot functions
source("templates/plot_functions.R")
# ============================================================================
# Example 1: Scatter Plot with Regression Line
# ============================================================================
# Simulated data
set.seed(42)
scatter_data <- data.frame(
x = rnorm(100, mean = 50, sd = 10),
y = rnorm(100, mean = 50, sd = 10)
)
scatter_data$y <- scatter_data$x * 0.8 + rnorm(100, sd = 5)
scatter_data$group <- sample(c("Control", "Treatment"), 100, replace = TRUE)
# Create scatter plot
p_scatter <- ggplot(scatter_data, aes(x = x, y = y, color = group)) +
geom_point(size = 3, alpha = 0.7) +
geom_smooth(method = "lm", se = TRUE, linewidth = 0.8) +
scale_color_manual(values = c("#E69F00", "#0072B2")) +
theme_publication() +
labs(x = "Independent Variable (units)",
y = "Dependent Variable (units)",
color = "Group")
# Save
save_publication_figure(p_scatter, "scatter_regression",
width = 89, height = 89,
formats = c("pdf", "png"))
# ============================================================================
# Example 2: Bar Plot with Error Bars
# ============================================================================
# Summary data for bar plot
bar_data <- data.frame(
category = c("A", "B", "C", "D"),
mean_value = c(25, 40, 35, 50),
se = c(3, 4, 3.5, 5)
)
# Create bar plot
p_bar <- ggplot(bar_data, aes(x = category, y = mean_value, fill = category)) +
geom_bar(stat = "identity", width = 0.7) +
geom_errorbar(aes(ymin = mean_value - se, ymax = mean_value + se),
width = 0.2, linewidth = 0.8) +
scale_fill_manual(values = okabe_ito[1:4]) +
theme_publication() +
labs(x = "Category",
y = "Mean Value ± SE",
fill = "Category") +
theme(legend.position = "none")
# Save
save_publication_figure(p_bar, "bar_with_error",
width = 89, height = 89,
formats = c("pdf", "png"))
# ============================================================================
# Example 3: Volcano Plot (Differential Expression)
# ============================================================================
# Simulated differential expression data
set.seed(42)
n_genes <- 1000
volcano_data <- data.frame(
gene = paste0("Gene", 1:n_genes),
log2FC = rnorm(n_genes, 0, 2),
pvalue = runif(n_genes, 0.0001, 1)
)
# Add significance
volcano_data <- volcano_data %>%
mutate(
neglog10p = -log10(pvalue),
significance = case_when(
log2FC >= 1 & pvalue < 0.05 ~ "Up",
log2FC <= -1 & pvalue < 0.05 ~ "Down",
TRUE ~ "NS"
)
)
# Create volcano plot
p_volcano <- ggplot(volcano_data, aes(x = log2FC, y = neglog10p)) +
geom_point(aes(color = significance), alpha = 0.6, size = 1.5) +
scale_color_manual(
values = c("Down" = "#0072B2", "NS" = "#999999", "Up" = "#D55E00"),
name = ""
) +
geom_vline(xintercept = c(-1, 1), linetype = "dashed", color = "grey50") +
geom_hline(yintercept = -log10(0.05), linetype = "dashed", color = "grey50") +
theme_publication() +
labs(x = expression(log[2]~Fold~Change),
y = expression(-log[10]~P~Value)) +
theme(legend.position = "right")
# Save
save_publication_figure(p_volcano, "volcano_plot",
width = 100, height = 89,
formats = c("pdf", "png"))
# ============================================================================
# Example 4: Box Plot
# ============================================================================
# Simulated data for box plot
set.seed(42)
box_data <- data.frame(
group = rep(c("Control", "Treatment A", "Treatment B"), each = 30),
value = c(rnorm(30, 20, 5), rnorm(30, 35, 8), rnorm(30, 30, 6))
)
# Create box plot
p_box <- ggplot(box_data, aes(x = group, y = value, fill = group)) +
geom_boxplot(outlier.shape = NA, width = 0.7) +
geom_point(position = position_jitter(width = 0.1),
size = 1.5, alpha = 0.5) +
scale_fill_manual(values = okabe_ito[1:3]) +
theme_publication() +
labs(x = "Group",
y = "Measured Value",
fill = "Group") +
theme(legend.position = "none")
# Save
save_publication_figure(p_box, "box_plot",
width = 89, height = 89,
formats = c("pdf", "png"))
# ============================================================================
# Example 5: Multi-Panel Figure (2x2 grid)
# ============================================================================
# Create four different plots for demonstration
p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(color = okabe_ito[1], size = 2, alpha = 0.7) +
geom_smooth(method = "lm", se = FALSE, color = "black") +
theme_publication(base_size = 10) +
labs(x = "Weight", y = "MPG", title = "A")
p2 <- ggplot(mtcars, aes(x = factor(cyl), y = hp, fill = factor(cyl))) +
geom_boxplot(outlier.shape = NA) +
geom_point(position = position_jitter(width = 0.1),
size = 1, alpha = 0.5) +
scale_fill_okabe_ito() +
theme_publication(base_size = 10) +
labs(x = "Cylinders", y = "Horsepower", title = "B") +
theme(legend.position = "none")
p3 <- ggplot(diamonds[sample(nrow(diamonds), 1000), ],
aes(x = carat, y = price)) +
geom_point(color = okabe_ito[2], size = 1, alpha = 0.5) +
theme_publication(base_size = 10) +
labs(x = "Carat", y = "Price", title = "C")
p4 <- ggplot(mtcars, aes(x = gear, fill = factor(am))) +
geom_bar(position = "fill") +
scale_fill_okabe_ito() +
theme_publication(base_size = 10) +
labs(x = "Gear", y = "Proportion", fill = "Transmission", title = "D")
# Combine into 2x2 grid
combined_figure <- (p1 | p2) / (p3 | p4)
# Save multi-panel figure
ggsave("results/figures/multipanel_2x2.pdf",
combined_figure,
width = 183, height = 183,
units = "mm", dpi = 600)
# ============================================================================
# Example 6: Line Plot (Time Series)
# ============================================================================
# Simulated time series data
set.seed(42)
time_points <- rep(1:10, 3)
line_data <- data.frame(
time = time_points,
value = c(
20 + time_points[1:10] + rnorm(10, 0, 2),
25 + time_points[1:10] * 1.2 + rnorm(10, 0, 3),
15 + time_points[1:10] * 0.8 + rnorm(10, 0, 2)
),
group = rep(c("Series A", "Series B", "Series C"), each = 10)
)
# Create line plot
p_line <- ggplot(line_data, aes(x = time, y = value, color = group)) +
geom_line(linewidth = 0.8) +
geom_point(size = 2.5) +
scale_color_manual(values = okabe_ito[1:3]) +
theme_publication() +
labs(x = "Time (hours)",
y = "Measured Value (arbitrary units)",
color = "Group") +
theme(legend.position = "top",
panel.grid.minor = element_line(color = "grey95"))
# Save
save_publication_figure(p_line, "line_plot",
width = 120, height = 89,
formats = c("pdf", "png"))
# ============================================================================
# Example 7: Heatmap (Correlation Matrix)
# ============================================================================
# Create correlation matrix
corr_matrix <- cor(mtcars[, c("mpg", "cyl", "disp", "hp", "wt", "qsec")])
# Convert to long format
corr_long <- expand.grid(dimnames(corr_matrix)) %>%
mutate(correlation = as.vector(corr_matrix),
Row = Var1, Col = Var2)
# Create heatmap
p_heat <- ggplot(corr_long, aes(x = Col, y = Row, fill = correlation)) +
geom_tile(color = "white", linewidth = 0.5) +
scale_fill_gradient2(low = "#0072B2", mid = "white", high = "#D55E00",
midpoint = 0, limits = c(-1, 1)) +
theme_publication() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "", y = "", fill = "Correlation")
# Save
save_publication_figure(p_heat, "heatmap",
width = 120, height = 100,
formats = c("pdf", "png"))
# ============================================================================
# Session Info
# ============================================================================
sessionInfo()
# ============================================================================
# Publication-Quality Plot Functions
# ============================================================================
# Description: Collection of functions for creating publication-ready plots
# Author: [Your name]
# Date: [Date]
# ============================================================================
# Required libraries ----------------------------------------------------------
library(ggplot2)
library(scales)
library(patchwork)
# Color-blind friendly palettes ---------------------------------------------
# Okabe-Ito palette (recommended for publications)
okabe_ito <- c(
"#E69F00", # Orange
"#56B4E9", # Sky blue
"#009E73", # Bluish green
"#F0E442", # Yellow
"#0072B2", # Blue
"#D55E00", # Vermillion
"#CC79A7", # Reddish purple
"#999999" # Grey
)
# Diverging palette for heatmaps/volcano plots
diverging_palette <- c("#D55E00", "#F0E442", "#999999", "#56B4E9", "#0072B2")
# ============================================================================
# Publication Theme
# ============================================================================
#' Publication-Ready ggplot2 Theme
#'
#' Creates a clean, publication-quality theme for ggplot2 figures
#' following common journal guidelines.
#'
#' @param base_size Base font size in points
#' @param base_family Base font family (Arial recommended for publications)
#' @return A ggplot theme object
#'
#' @examples
#' ggplot(mtcars, aes(x = wt, y = mpg)) +
#' geom_point() +
#' theme_publication()
theme_publication <- function(base_size = 12, base_family = "Arial") {
theme_bw(base_size = base_size, base_family = base_family) +
theme(
# Legend placement
legend.position = "top",
legend.title = element_text(size = rel(1)),
legend.text = element_text(size = rel(0.9)),
legend.key.size = unit(0.4, "cm"),
legend.margin = margin(0, 0, 0, 0, "cm"),
legend.box.margin = margin(0, 0, -5, 0, "mm"),
# Panel borders
panel.border = element_rect(size = 0.5, color = "black"),
panel.grid.major = element_line(color = "grey90", linewidth = 0.25),
panel.grid.minor = element_blank(),
# Axis text
axis.text = element_text(size = rel(0.9), color = "black"),
axis.title = element_text(size = rel(1)),
# Plot elements
plot.title = element_text(size = rel(1.2), hjust = 0.5),
# Strip text for facets
strip.background = element_rect(color = "black", fill = "grey90"),
strip.text = element_text(size = rel(0.9))
)
}
# ============================================================================
# Scale Functions
# ============================================================================
#' Okabe-Ito Color Scale
#'
#' Applies the color-blind friendly Okabe-Ito palette
#'
#' @param palette Number of colors to use (1-8)
#'
scale_color_okabe_ito <- function(palette = 8) {
discrete_scale("colour", "okabe_ito",
function(n) okabe_ito[1:min(n, 8)])
}
scale_fill_okabe_ito <- function(palette = 8) {
discrete_scale("fill", "okabe_ito",
function(n) okabe_ito[1:min(n, 8)])
}
# ============================================================================
# Export Functions
# ============================================================================
#' Save Publication-Quality Figure
#'
#' Exports a ggplot object to publication-ready formats with proper
#' dimensions and resolution.
#'
#' @param plot ggplot object to save
#' @param filename Output filename (without extension)
#' @param path Output directory path
#' @param width Width in mm
#' @param height Height in mm
#' @param dpi Resolution for raster formats (default: 600)
#' @param formats Vector of formats: c("pdf", "png", "svg", "tiff")
#'
#' @examples
#' p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
#' save_publication_figure(p, "scatter_plot",
#' width = 89, height = 89,
#' formats = c("pdf", "png"))
save_publication_figure <- function(plot,
filename,
path = "results/figures",
width = 89,
height = 89,
dpi = 600,
formats = c("pdf")) {
# Create output directory if needed
if (!dir.exists(path)) {
dir.create(path, recursive = TRUE)
}
# Export in each requested format
for (fmt in formats) {
filepath <- file.path(path, paste0(filename, ".", fmt))
ggsave(filepath, plot = plot,
width = width, height = height,
units = "mm", dpi = dpi,
device = fmt)
message("Saved: ", filepath)
}
}
# ============================================================================
# Specific Plot Functions
# ============================================================================
#' Create Scatter Plot with Regression
#'
#' @param data Data frame
#' @param x x-axis variable
#' @param y y-axis variable
#' @param color Color/group variable (optional)
#' @param add_regression Add regression line
#' @param show_ci Show confidence interval
#'
create_scatter_plot <- function(data, x, y, color = NULL,
add_regression = TRUE, show_ci = TRUE) {
x_sym <- enquo(x)
y_sym <- enquo(y)
p <- ggplot(data, aes(x = !!x_sym, y = !!y_sym))
if (is.null(color)) {
p <- p + geom_point(size = 3, alpha = 0.7)
if (add_regression) {
if (show_ci) {
p <- p + geom_smooth(method = "lm", se = TRUE, color = "black")
} else {
p <- p + geom_smooth(method = "lm", se = FALSE, color = "black")
}
}
} else {
color_sym <- enquo(color)
p <- p + geom_point(aes_string(color = color), size = 3, alpha = 0.7) +
scale_color_okabe_ito()
if (add_regression) {
if (show_ci) {
p <- p + geom_smooth(aes_string(color = color),
method = "lm", se = TRUE)
} else {
p <- p + geom_smooth(aes_string(color = color),
method = "lm", se = FALSE)
}
}
}
p + theme_publication()
}
#' Create Bar Plot with Error Bars
#'
#' @param data Data frame
#' @param x x-axis variable (categorical)
#' @param y y-axis variable (numeric)
#' @param fill Fill variable (optional)
#' @param error_var Error bar variable (optional)
#'
create_bar_plot <- function(data, x, y, fill = NULL, error_var = NULL) {
x_sym <- enquo(x)
y_sym <- enquo(y)
p <- ggplot(data, aes(x = !!x_sym, y = !!y_sym, group = !!x_sym))
if (is.null(fill)) {
p <- p + geom_bar(stat = "identity", fill = okabe_ito[1], width = 0.7)
} else {
fill_sym <- enquo(fill)
p <- p + geom_bar(aes_string(fill = fill),
stat = "identity", width = 0.7, position = "dodge") +
scale_fill_okabe_ito()
}
if (!is.null(error_var)) {
p <- p + geom_errorbar(aes_string(ymin = paste0(y, "-", error_var),
ymax = paste0(y, "+", error_var)),
width = 0.2)
}
p + theme_publication() +
labs(y = deparse(substitute(y)), x = deparse(substitute(x)))
}
#' Create Volcano Plot
#'
#' @param data Data frame with log2FC and p-value columns
#' @param logfc Column name for log2 fold change
#' @param pval Column name for p-value
#' @param fc_threshold Fold change threshold
#' @param p_threshold P-value threshold
#'
create_volcano_plot <- function(data, logfc = "log2FC", pval = "pvalue",
fc_threshold = 1, p_threshold = 0.05) {
# Calculate -log10(p-value)
data <- data %>%
mutate(neglog10p = -log10(!!sym(pval)),
significance = case_when(
abs(!!sym(logfc)) >= fc_threshold & !!sym(pval) < p_threshold ~ "Up",
abs(!!sym(logfc)) >= fc_threshold & !!sym(pval) < p_threshold ~ "Down",
TRUE ~ "NS"
))
p <- ggplot(data, aes(x = !!sym(logfc), y = neglog10p)) +
geom_point(aes(color = significance), alpha = 0.6, size = 1.5) +
scale_color_manual(values = c("Down" = "#0072B2",
"NS" = "#999999",
"Up" = "#D55E00"),
name = "") +
geom_vline(xintercept = c(-fc_threshold, fc_threshold),
linetype = "dashed", color = "grey50") +
geom_hline(yintercept = -log10(p_threshold),
linetype = "dashed", color = "grey50") +
theme_publication() +
labs(x = expression(log[2]~Fold~Change),
y = expression(-log[10]~P~Value))
return(p)
}
#' Create Box Plot
#'
#' @param data Data frame
#' @param x x-axis variable (categorical)
#' @param y y-axis variable (numeric)
#' @param fill Fill variable (optional)
#'
create_box_plot <- function(data, x, y, fill = NULL) {
x_sym <- enquo(x)
y_sym <- enquo(y)
p <- ggplot(data, aes(x = !!x_sym, y = !!y_sym, group = !!x_sym))
if (is.null(fill)) {
p <- p + geom_boxplot(fill = okabe_ito[1], outlier.shape = NA) +
geom_point(position = position_jitter(width = 0.1), size = 1, alpha = 0.5)
} else {
fill_sym <- enquo(fill)
p <- p + geom_boxplot(aes_string(fill = fill),
outlier.shape = NA) +
geom_point(position = position_jitterdodge(dodge.width = 0.75),
size = 1, alpha = 0.5) +
scale_fill_okabe_ito()
}
p + theme_publication()
}
# ============================================================================
# Session Info
# ============================================================================
# For reproducibility
sessioninfo::session_info()
# ============================================================================
# R Project Initialization Script
# ============================================================================
# This script sets up a new R research project with proper directory structure
# and package management using renv.
#
# Usage: Run this script at the start of a new project
# ============================================================================
# Setup message
message("Setting up R research project...")
# Create directory structure
dirs <- c(
"data/raw",
"data/processed",
"scripts",
"results/figures",
"results/tables",
"results/models",
"reports",
"docs"
)
for (dir in dirs) {
if (!dir.exists(dir)) {
dir.create(dir, recursive = TRUE)
message("Created directory: ", dir)
}
}
# Create .gitkeep files for empty directories
gitkeep_dirs <- c(
"data/raw/.gitkeep",
"data/processed/.gitkeep",
"results/figures/.gitkeep",
"results/tables/.gitkeep",
"results/models/.gitkeep",
"reports/.gitkeep"
)
for (file in gitkeep_dirs) {
if (!file.exists(file)) {
write("", file = file)
}
}
# Initialize renv if not already initialized
if (!file.exists("renv.lock")) {
if (interactive()) {
response <- readline("Initialize renv for package management? (y/n): ")
if (tolower(response) == "y") {
renv::init()
message("renv initialized. Remember to snapshot your packages:")
message(" renv::snapshot()")
}
} else {
renv::init()
message("renv initialized. Remember to snapshot your packages:")
message(" renv::snapshot()")
}
}
# Create .Rproj file if using RStudio
if (!file.exists(paste0(getwd(), ".Rproj"))) {
if (requireNamespace("rstudioapi", quietly = TRUE) && rstudioapi::isAvailable()) {
rstudioapi::createProject(getwd())
message("Created RStudio project file")
}
}
# Create a basic README
if (!file.exists("README.md")) {
readme_content <- c(
"# Project Title",
"",
"## Description",
"",
"Brief description of the research project.",
"",
"## Project Structure",
"",
"```",
".",
"|-- data/",
"| |-- raw/ # Original, immutable data",
"| |-- processed/ # Cleaned, transformed data",
"|-- scripts/ # Analysis scripts",
"|-- results/",
"| |-- figures/ # Plots and visualizations",
"| |-- tables/ # Summary tables",
"| |-- models/ # Saved model objects",
"|-- reports/ # R Markdown/Quarto reports",
"|-- docs/ # Additional documentation",
"```",
"",
"## Setup",
"",
"```r",
"# Install and activate renv",
"renv::restore()",
"```",
"",
"## Usage",
"",
"## References",
""
)
writeLines(readme_content, "README.md")
message("Created README.md")
}
message("\n=== Project setup complete! ===")
message("\nNext steps:")
message("1. Add your data to data/raw/")
message("2. Create analysis scripts in scripts/")
message("3. Use renv::install() to add required packages")
message("4. Run renv::snapshot() to save your package state")
{
"R": {
"Version": "4.3.2",
"Platforms": [
{
"Platform": "x86_64-pc-linux-gnu",
"Path": "library"
}
]
},
"Packages": {
" tidyverse ": " {
"Package": "tidyverse",
"Version": "2.0.0",
"Source": "Repository",
"Repository": "CRAN",
"Hash": "abc123..."
},
"ggplot2": {
"Package": "ggplot2",
"Version": "3.4.4",
"Source": "Repository",
"Repository": "CRAN",
"Hash": "def456..."
},
"dplyr": {
"Package": "dplyr",
"Version": "1.1.3",
"Source": "Repository",
"Repository": "CRAN",
"Hash": "ghi789..."
}
}
}
---
title: "Report Title"
author: "Author Name"
date: "`r Sys.Date()`"
format:
html:
theme: cosmo
toc: true
code-fold: true
code-tools: true
pdf:
toc: true
number-sections: true
engine: knitr
---
# Introduction
Brief description of the research question and objectives.
# Methods
## Data Preparation
```{r}
# Load libraries
library(tidyverse)
library(here)
```
Describe the data processing steps.
## Analysis
```{r}
# Your analysis code here
```
# Results
```{r}
# Results
```
# Discussion
Interpretation of results and conclusions.
# Session Info
```{r}
sessionInfo()
```
# References
---
## Appendices
### Additional Analyses
```{r}
# Additional code
```