r-for-analysis
Writes idiomatic tidyverse R for data analysis - dplyr wrangling pipelines, tidyr reshaping, explicit joins, layered ggplot2 visualization, and broom-tidied statistical models - with reproducibility practices baked in. Use when someone asks "write this analysis in R", "how do I pivot this data frame", "fit a regression per group in R", or wants messy base-R scripts converted to clean pipe-based tidyverse code. Do NOT use for Python-based dataframe work - use pandas-expert instead; for interpreting results for stakeholders use sql-to-insights.
- License 许可
- MIT
- 最近更新
- 2026-10-14
- Stars
- ★ 25
- Forks
- 3
01 前言 Front Matter
- name
- r-for-analysis
- metadata
- { "title": "R for Analysis" }
- description
- Writes idiomatic tidyverse R for data analysis - dplyr wrangling pipelines, tidyr reshaping, explicit joins, layered ggplot2 visualization, and broom-tidied statistical models - with reproducibility practices baked in. Use when someone asks "write this analysis in R", "how do I pivot this data frame", "fit a regression per group in R", or wants messy base-R scripts converted to clean pipe-based tidyverse code. Do NOT use for Python-based dataframe work - use pandas-expert instead; for interpreting results for stakeholders use sql-to-insights.
03 SKILL.md 正文
R for Analysis
Produce R analysis code that another analyst can re-run a year later and get the same answer. The costly mistake this prevents: interactive one-off scripts with silent type inference, implicit grouping, and unseeded randomness - code that works once on one laptop and never again.
Inputs to collect
Before writing code, establish:
- The data source and its shape - file, database, or in-memory; roughly how many rows (millions of rows change the tool choice: consider data.table or duckdb backends past ~10M rows).
- The analytical question in one sentence. If the user cannot state it, help them state it first - code without a question produces plots without a point.
- The output target - exploratory notebook, Quarto report, or a table/figure for a deck. This decides how much polish the code needs.
Label any assumption about column meanings as a guess and confirm against a glimpse() of the real data.
Operating procedure
Work in this order - each step protects the ones after it.
Step 1: Reproducible setup
library(tidyverse)
library(lubridate)
library(broom)
set.seed(42) # any stochastic operation must be seeded
Step 2: Read with explicit types
Never trust type inference on data that matters:
sales <- read_csv("sales.csv", col_types = cols(
date = col_date(),
amount = col_double(),
region = col_character()
))
Immediately glimpse(sales) and check row count against expectation. Standardize names with janitor::clean_names().
Step 3: Validate before analyzing
Encode assumptions as executable checks, not comments:
stopifnot(
nrow(sales) > 0,
!any(is.na(sales$date)),
all(sales$amount >= 0 | is.na(sales$amount))
)
A check that fails loudly today beats a wrong number in a deck next week.
Step 4: Wrangle with one-verb-per-line pipelines
summary_tbl <- sales %>%
filter(amount > 0) %>%
mutate(month = floor_date(date, "month")) %>%
group_by(region, month) %>%
summarise(total = sum(amount), n = n(), .groups = "drop") %>%
arrange(region, month)
Rules that prevent the classic silent errors:
- Always pass
.groups = "drop"tosummarise()- silently grouped output corrupts every downstream step. - Joins take an explicit
by; checknrow()before and after every join for unexpected row multiplication. - Prefer
case_when()over nestedifelse(); keep raw data immutable and create new objects per transformation stage.
Step 5: Reshape only at the boundary
Keep data long for analysis; pivot wide only for presentation:
wide <- summary_tbl %>% pivot_wider(names_from = region, values_from = total)
Step 6: Visualize in layers
ggplot(summary_tbl, aes(month, total, color = region)) +
geom_line(linewidth = 1) +
scale_y_continuous(labels = scales::comma) +
labs(title = "Monthly sales by region", x = NULL, y = "Total") +
theme_minimal()
Map variables inside aes(), set constants outside it. Every axis gets human-readable labels and formatted scales before anyone else sees the plot.
Step 7: Model and tidy the output
model <- lm(total ~ month + region, data = summary_tbl)
tidy(model, conf.int = TRUE)
glance(model)
For group-wise models, nest and map rather than looping:
models <- sales %>%
group_by(region) %>%
nest() %>%
mutate(fit = map(data, ~ lm(amount ~ date, data = .x)),
tidied = map(fit, tidy)) %>%
unnest(tidied)
Report coefficients with confidence intervals, never bare point estimates. Say "associated with", not "causes", unless the design supports causal claims - route causal questions to causal-inference.
Step 8: Package for reproduction
Deliver as a Quarto or R Markdown document that runs top to bottom in a fresh session. If it only runs after manual steps, it is not done.
Good / bad
Bad: df2 <- df[df$amt > 0 & !is.na(df$amt),]; agg <- aggregate(amt ~ reg, df2, sum) - base-R index gymnastics, no types checked, unreadable in review.
Good: the Step 4 pipeline - each verb does one thing, grouping is explicit and dropped, and the intent reads top to bottom.
Deliverable
Produce a runnable script or Quarto document containing: seeded setup, typed data import, stopifnot() validation block, pipelined transformations, labeled publication-ready plots, tidied model output with confidence intervals, and a one-paragraph plain-language answer to the analytical question.
Do NOT
- Do not rely on
read_csv()type inference for anything that feeds a decision - a column silently read as character has ruined many aggregates. - Do not leave
summarise()output grouped;.groups = "drop"every time. - Do not join without checking row counts - a many-to-many join inflates sums silently.
- Do not report model point estimates without intervals, or imply causation from observational fits.
- Do not mix analysis and presentation shapes - keep data long until the final table.
Quality bar
The analysis ships only when: it runs top to bottom in a fresh R session with no manual steps; every stochastic step is seeded; every assumption about the data is a stopifnot() check; every plot has labeled axes and formatted scales; and the answer to the original question appears in plain language, not just in a table.
04 同仓库更多 Skills
zone-2-cardio-plan
Use when someone asks to build a steady-state cardio plan, train an aerobic base or Zone 2, structure easy or endurance weekly cardio, train by heart-rate zones, or improve resting heart rate, VO2, or endurance. Builds a heart-rate-zone aerobic training block with session structure, modality choice, and progression. General fitness guidance, not medical advice. Do NOT use to design a strength or lifting program (use Strength Training Plan), high-intensity interval conditioning, HIIT, or circuits (use Conditioning & HIIT Program), or a mobility/flexibility routine (use Mobility Routine).
youtube-script-writer
Writes retention-engineered long-form YouTube scripts on a hook/body/payoff architecture - a first-30-seconds hook that survives the retention cliff, a beat-sheet body with mini-hooks and bridges, timed pattern interrupts, and a payoff that over-delivers - with B-roll and editing cues marked inline. Use when someone says "script my next video", "my retention graph dies at the start", "tighten this draft", or "outline a video on X". Do NOT use for the 3-second opener of TikTok, Reels, or Shorts - use video-hook-writer instead; do NOT use for spoken voiceover synced to on-screen tutorial actions - use narration-script instead; do NOT use for a sales demo built on a buyer's discovery notes - use demo-script instead; do NOT use to design the thumbnail and title - use thumbnail-concept instead.
win-back-campaign
Designs segmented win-back email sequences for dormant users - dormancy tiers, a three-beat sequence with a single proportional incentive, and a suppression rule - and measures success by re-activation, not opens. Use when someone says "our users went quiet", "design a win-back campaign", "how do I re-engage lapsed customers", "should we email people who haven't logged in for months", or lifecycle messaging has stopped landing with a lapsed segment. Do NOT use for recovering an unfinished checkout - use abandoned-cart-sequence instead. Do NOT use for diagnosing and fixing why active customers cancel - use churn-reduction instead. Do NOT use for building always-on onboarding or nurture flows - use email-drip-builder instead.
wikipedia-style
Writes neutral, verifiable, encyclopedic prose following Wikipedia's core content policies and manual of style - NPOV, inline citations, notability-backed claims, and a strict ban on promotional language. Use when someone asks "write this like a Wikipedia article", "draft a Wikipedia page for this company or person", "make this neutral and encyclopedic", or "why does my article draft keep getting rejected". Do NOT use for persuasive or opinion writing - use op-ed-writer instead; for thesis-driven academic papers, use academic-essay; for verifying claims in existing text, use fact-checker.
whitepapers
Structures and writes authoritative B2B whitepapers - a standalone executive summary, a data-sized problem statement, methodology, evidence-driven findings, recommendations, and a soft call to action - flagging every claim that needs a real citation. Use when a marketer asks "write a whitepaper on this topic", "turn our research into a lead-gen asset", "make this credible enough for executives", or a draft reads like a product pitch instead of analysis. Do NOT use for customer-story-driven proof - use case-study-builder instead; for policy audiences, use policy-brief.
white-space-analysis
Finds unmet market gaps by ranking jobs-to-be-done on importance versus satisfaction, overlaying them against current solutions and workarounds, and validating that each gap is real, winnable, and worth winning. Use when someone asks "where are the gaps in this market", "what's underserved here", "where should we play next", or is hunting for product, feature, or market-entry opportunities. Do NOT use for profiling competitors and building battle cards - use competitive-intelligence instead; for putting a dollar figure on an identified opportunity - use market-sizing instead; for extracting jobs-to-be-done from raw customer interviews - use jtbd-extractor instead.