agentleFS
nurlan135nurlan135/stats-skill-for-ai-agents/SKILL.md

statistical-analysis

Skill0 starsChanged 2 months agoMITView on GitHub

Statistical analysis service. Trigger conditions: (1) Upload a data file, (2) Say "statistical analysis" / "analyze my data" / "run the data", (3) Mention a specific statistical method (t-test / regression / SEM, etc.).

  • Installs packages

20 other projects use a version of this, 1 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use venue-templates, scientific-critical-thinking and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • ZanderRussSkill

    venue-templates

    Access comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.

    Also in 4 projects that use this

  • ZanderRussSkill

    scientific-critical-thinking

    Evaluate research rigor. Assess methodology, experimental design, statistical validity, biases, confounding, evidence quality (GRADE, Cochrane ROB), for critical analysis of scientific claims.

    Also in 5 projects that use this

  • sahinSkill

    peer-review

    Also in 4 projects that use this

  • AnthropicSkill

    xlsx

    Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas

    Also in 4 projects that use this

  • AnthropicSkill

    docx

    Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks

    Also in 4 projects that use this

  • MicrosoftSkill

    mcp-builder

    Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

    Also in 4 projects that use this

  • +6 more from ZanderRuss

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 17 edited versions we read keep these.

  • 3

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Check normality and homogeneity (Levene) before t-tests.

    line 163
  2. Distinctive:

    No data file needed. Ask for: method, expected effect size (default medium), alpha (.05), power (.80), groups, one/two-tailed.

    line 208
  3. Very specific:

    Every analysis must produce all three.

    line 218
  4. Distinctive:

    Always alert the user when missingness exceeds 5%.

    line 245

“Common” is measured: kept by at least 6 in 10 of the 17 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Statistical Analysis Service

Core Philosophy: Diagnosis Before Analysis

Handle messy real-world tables first, then diagnose data and assumptions.

User request → Ingest (csv/xlsx/docx) → Data profile → Assumption checks → Intelligent method selection → Execute → Triplet output (table + figure + paragraph)

Workflow Overview

User request
    |
    v
+-------------------------------------+
|  Step 0: Data Profile (required for  |
|          all paths)                  |
|  - Sample size, variable types,      |
|    missing patterns                  |
|  - Distribution characteristics,     |
|    outlier detection                 |
|  - Completed within 30 seconds,      |
|    no confirmation needed            |
+-------------------------------------+
    |
    v
Assess complexity -> Select path
    |
    |-- Quick path -> Assumption self-check -> Execute -> Triplet output
    |-- Light path -> Assumption self-check -> Confirm variables -> Execute -> Triplet output
    +-- Full path  -> Four stages (incl. assumption checks) -> Triplet output

Step 0: Data Profile

Must be executed before all analyses. Output format:

## Data Profile

| Metric | Value |
|--------|-------|
| Sample size | N = 3248 |
| Variables | 94 (continuous: 60, categorical: 34) |
| Missing rate | Overall 2.3%, highest: Variable X (15.2%) |
| Outliers | Variable Y has 12 (> 3SD) |

### Key Variable Distributions
| Variable | M (SD) | Skewness | Kurtosis | Normality |
|----------|--------|----------|----------|-----------|
| DV_score | 3.45 (1.23) | 0.34 | -0.12 | Pass |
| IV_score | 2.89 (0.98) | 1.45 | 3.21 | Right-skewed |

### Data Alerts
- Warning: IV_score is right-skewed; parametric tests should be used with caution
- Warning: Variable X has 15% missing; recommend checking MCAR/MAR
- OK: Sample size is sufficient for all standard analyses

Execution code (runs automatically, not displayed to the user):

import pandas as pd
import numpy as np
from scipy import stats

# pip install: scipy statsmodels pingouin matplotlib seaborn scikit-learn python-docx
df = pd.read_excel("data.xlsx")  # or pd.read_csv("data.csv")

def parse_num(x):
    # Handles decimal comma, nbsp, and '-'/'–'/'—'/'' as missing
    if x is None or (isinstance(x, float) and np.isnan(x)):
        return np.nan
    s = str(x).strip().replace('\xa0', '')
    if s in ('', '-', '–', '—', 'nan', 'None'):
        return np.nan
    return float(s.replace(',', '.'))

# Word tables: read via python-docx, never copy-paste
import docx
doc = docx.Document("report.docx")
for ti, t in enumerate(doc.tables):
    rows = [[c.text.strip() for c in r.cells] for r in t.rows]
    pd.DataFrame(rows[1:], columns=rows[0]).to_csv(
        f"table{ti+1}_raw.csv", index=False, encoding="utf-8-sig")

def data_profile(df, target_vars=None):
    """Generate data profile; target_vars are key variables mentioned by the user"""
    vars_to_check = target_vars or df.select_dtypes(include=[np.number]).columns[:10]

    profile = {}
    for var in vars_to_check:
        col = df[var].dropna()
        n = len(col)
        # Normality test: Shapiro-Wilk for n<50, skewness+kurtosis for n>=50
        skew, kurt = col.skew(), col.kurtosis()
        if n < 50:
            _, p_norm = stats.shapiro(col)
            is_normal = p_norm > .05
        else:
            is_normal = abs(skew) < 2 and abs(kurt) < 7

        profile[var] = {
            'M': col.mean(), 'SD': col.std(),
            'missing': df[var].isna().sum(),
            'missing_pct': df[var].isna().mean() * 100,
            'skew': skew, 'kurt': kurt,
            'is_normal': is_normal,
            'outliers_3sd': ((col - col.mean()).abs() > 3 * col.std()).sum()
        }
    return profile

def format_p(p):
    if p < .001:
        return "< .001"
    return f"= {p:.3f}"

Non-tidy / Hierarchical Tables (mandatory check)

Official statistics tables are often NOT tidy data. See references/official-tables.md for the full checklist. Summary: (1) drop total/aggregate rows, (2) analyse leaf-level units only, (3) flag non-independence — parent and child double-count the same output, so paired t/Wilcoxon p-values are descriptive, not strict inference. State this caveat in the result paragraph. With small N (< 20 groups) prefer effect sizes + CIs over binary significance claims.


Complexity Assessment and Path Selection

ComplexityAnalysis TypePathConfirmations
SimpleDescriptive statistics, t-test, chi-square, correlation, reliability/validity, ICCQuick0
ModerateRegression, ANOVA, moderation, mediation, ROC/AUC, survival analysisLight1
ComplexSEM/CFA, HLM, IRT, meta-analysis, RI-CLPM, propensity score matchingFull3-4
PlanningSample size calculation / Power Analysis (no data, parameters only)Dedicated1

Quick Path

Data profile → assumption self-check → execute → triplet output.

Check normality and homogeneity (Levene) before t-tests. If assumptions fail, automatically switch to the non-parametric alternative (e.g. Mann-Whitney U) and tell the user why:

> Note: Variable X failed normality (Shapiro-Wilk p = .003). Switched to Mann-Whitney U test.

Method details: see references/methods-index.md. Code patterns: see references/code-patterns.md.


Multiple Comparisons + Small-N + Nominal/Real (mandatory)

  • 3+ group/sector comparisons → report Holm-adjusted p-values alongside raw p (statsmodels multipletests, method='holm').
  • Small N (< 20 groups or n < 30): always report effect size + 95% CI next to p; state achieved power is low and treat p as exploratory.
  • Monetary values across years are nominal unless a deflator/CPI is documented — say so explicitly (e.g. "nominal +5.4%; real change unknown without deflator") and never present nominal growth as real.

Light Path

Data profile → assumption self-check → confirm variable roles → execute → triplet output.

Show a confirmation table with Y, X, moderator, controls plus distribution and assumption warnings (VIF, skewness, sample size). Recommend fixes (log transform, robust SE HC3) before proceeding.


Full Path (complex analysis)

Work in four confirmed stages — see references/full-workflow.md for output templates: (1) data profile + cleaning plan, (2) cleaning + assumption checks, (3) analysis plan + sample adequacy, (4) execute → triplet output. Pause for confirmation at each stage.


Power Analysis Path

No data file needed. Ask for: method, expected effect size (default medium), alpha (.05), power (.80), groups, one/two-tailed. Then compute required N. Quick reference (per group unless noted): t-test medium d=0.5 → 64; ANOVA 3-group medium f=0.25 → 159; correlation medium r=.30 → 85; regression 3-IV medium f²=.15 → 77.


Required Output Triplet

Every analysis must produce all three. Table formats: see references/table-formats.md. Report template: see assets/report-template.md.

  1. APA table (Markdown; Excel on request): stats 2 decimals, p 3 decimals (< .001), stars *p<.05 **p<.01 ***p<.001, effect sizes, 95% CI.
  2. Figure (PNG, dpi=300): t-test → grouped bars with error bars; correlation → heatmap; regression → coefficient forest plot; moderation → simple slopes; mediation → path diagram; ANOVA → boxplot; ROC → ROC curve; survival → Kaplan-Meier curve.
  3. Result paragraph (English; Azerbaijani on request): ready to paste into a manuscript. Templates:
    • t-test: "An independent samples t-test revealed a significant difference in {DV} between {g1} (M = .., SD = ..) and {g2} (M = .., SD = ..), t(df) = .., p .., Cohen's d = ... The effect size was {small/medium/large}."
    • Correlation: "Pearson correlation showed {X} was significantly {positively/negatively} correlated with {Y}, r(df) = .., p ...."
    • Regression: report R², F, ΔR², ΔF, β per step.
    • Mediation: indirect effect + 95% bootstrap CI, direct effect, full/partial mediation.
    • Moderation: interaction B/SE/p + simple slopes at ±1SD.

Figure setup: matplotlib.use('Agg'), dpi=300, savefig.bbox='tight', seaborn style white.


Missing Data Strategy

Missing rateStrategy
< 5%listwise deletion
5–20%multiple imputation (MICE), report sensitivity
> 20%check MCAR first, then decide

Always alert the user when missingness exceeds 5%.


Method–Library Quick Reference

MethodLibrary
descriptivespandas describe()
t-test, chi-square, correlationscipy
regression, ANOVA interactionstatsmodels
ANOVA, reliability (Cronbach α), ICCpingouin
ROC/AUCsklearn
survivallifelines
SEM (basic), HLM (2-level)semopy, statsmodels
SEM/HLM/IRT/meta beyond Pythonstandalone .R script for RStudio

Complex needs beyond Python get a standalone .R script for RStudio.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.