{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-stats-analysis-af895d9c60d6","title":"Statistical Analysis for Comparing Groups and Variables","summary":"Perform t-tests, ANOVA, correlation analysis, and multiple testing corrections using Python libraries like scipy and statsmodels. This skill supports statistical hypothesis testing and works with any LLM provider.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-stats-analysis-af895d9c60d6","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-stats-analysis-af895d9c60d6","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-stats-analysis-af895d9c60d6.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-stats-analysis-af895d9c60d6\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Ensure that the required Python libraries (scipy, statsmodels, numpy) are installed in your environment before running the statistical tests. Additionally, provide numeric data arrays or datasets as input for the analysis.","instructions":"---\nname: data-stats-analysis\ndescription: Perform statistical tests, hypothesis testing, correlation analysis, and multiple testing corrections using scipy and statsmodels. Works with ANY LLM provider (GPT, Gemini, Claude, etc.).\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n\n# Statistical Analysis (Universal)\n\n## Overview\nThis skill enables you to perform rigorous statistical analyses including t-tests, ANOVA, correlation analysis, hypothesis testing, and multiple testing corrections. Unlike cloud-hosted solutions, this skill uses standard Python statistical libraries (**scipy**, **statsmodels**, **numpy**) and executes **locally** in your environment, making it compatible with **ALL LLM providers** including GPT, Gemini, Claude, DeepSeek, and Qwen.\n\n## When to Use This Skill\n- Compare means between groups (t-tests, ANOVA)\n- Test for correlations between variables\n- Perform hypothesis testing with p-value calculation\n- Apply multiple testing corrections (FDR, Bonferroni)\n- Calculate statistical summaries and confidence intervals\n- Test for normality and distribution fitting\n- Perform non-parametric tests (Mann-Whitney, Kruskal-Wallis)\n\n## How to Use\n\n### Step 1: Import Required Libraries\n```python\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nfrom scipy.stats import ttest_ind, mannwhitneyu, pearsonr, spearmanr\nfrom scipy.stats import f_oneway, kruskal, chi2_contingency\nfrom statsmodels.stats.multitest import multipletests\nfrom statsmodels.stats.proportion import proportions_ztest\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n### Step 2: Two-Sample t-Test\n```python\n# Compare means between two groups\n# group1, group2: arrays of numeric values\n\n# Perform independent t-test\nt_statistic, p_value = ttest_ind(group1, group2)\n\nprint(f\"t-statistic: {t_statistic:.4f}\")\nprint(f\"p-value: {p_value:.4e}\")\n\nif p_value < 0.05:\n    print(\"\u2705 Significant difference between groups (p < 0.05)\")\nelse:\n    print(\"\u274c No significant difference (p >= 0.05)\")\n\n# With equal variance assumption check\n# Levene's test for equal variances\n_, levene_p = stats.levene(group1, group2)\nif levene_p < 0.05:\n    # Use Welch's t-test (unequal variances)\n    t_stat, p_val = ttest_ind(group1, group2, equal_var=False)\n    print(f\"Welch's t-test p-value: {p_val:.4e}\")\nelse:\n    print(\"Equal variances assumed\")\n```\n\n### Step 3: One-Way ANOVA\n```python\n# Compare means across multiple groups\n# groups: list of arrays, e.g., [group1, group2, group3]\n\n# Perform one-way ANOVA\nf_statistic, p_value = f_oneway(*groups)\n\nprint(f\"F-statistic: {f_statistic:.4f}\")\nprint(f\"p-value: {p_value:.4e}\")\n\nif p_value < 0.05:\n    print(\"\u2705 Significant difference between groups (p < 0.05)\")\n    print(\"Note: Use post-hoc tests to identify which groups differ\")\nelse:\n    print(\"\u274c No significant difference between groups\")\n\n# Post-hoc pairwise t-tests with Bonferroni correction\nfrom itertools import combinations\n\ngroup_names = ['Group A', 'Group B', 'Group C']\npairwise_results = []\n\nfor (name1, data1), (name2, data2) in combinations(zip(group_names, groups), 2):\n    _, p = ttest_ind(data1, data2)\n    pairwise_results.append({\n        'comparison': f'{name1} vs {name2}',\n        'p_value': p\n    })\n\n# Apply Bonferroni correction\npairwise_df = pd.DataFrame(pairwise_results)\nn_tests = len(pairwise_df)\npairwise_df['p_adjusted'] = pairwise_df['p_value'] * n_tests\npairwise_df['p_adjusted'] = pairwise_df['p_adjusted'].clip(upper=1.0)\n\nprint(\"\\nPairwise Comparisons (Bonferroni-corrected):\")\nprint(pairwise_df)\n```\n\n### Step 4: Correlation Analysis\n```python\n# Pearson correlation (linear relationships)\nr_pearson, p_pearson = pearsonr(variable1, variable2)\n\nprint(f\"Pearson correlation: r = {r_pearson:.4f}, p = {p_pearson:.4e}\")\n\n# Spearman correlation (monotonic relationships, robust to outliers)\nr_spearman, p_spearman = spearmanr(variable1, variable2)\n\nprint(f\"Spearman correlation: \u03c1 = {r_spearman:.4f}, p = {p_spearman:.4e}\")\n\n# Interpretation\nif abs(r_pearson) < 0.3:\n    strength = \"weak\"\nelif abs(r_pearson) < 0.7:\n    strength = \"moderate\"\nelse:\n    strength = \"strong\"\n\ndirection = \"positive\" if r_pearson > 0 else \"negative\"\nprint(f\"Interpretation: {strength} {direction} correlation\")\n\nif p_pearson < 0.05:\n    print(\"\u2705 Statistically significant (p < 0.05)\")\nelse:\n    print(\"\u274c Not statistically significant\")\n```\n\n### Step 5: Multiple Testing Correction\n```python\n# Scenario: Testing 1000 genes for differential expression\n# p_values: array of p-values from individual tests\n\n# Method 1: Benjamini-Hochberg FDR correction (recommended)\nreject_fdr, p_adjusted_fdr, _, _ = multipletests(p_values, alpha=0.05, method='fdr_bh')\n\n# Method 2: Bonferroni correction (more conservative)\nreject_bonf, p_adjusted_bonf, _, _ = multipletests(p_values, alpha=0.05, method='bonferroni')\n\n# Create results DataFrame\nresults_df = pd.DataFrame({\n    'gene': gene_names,\n    'p_value': p_values,\n    'q_value_fdr': p_adjusted_fdr,\n    'p_adjusted_bonferroni': p_adjusted_bonf,\n    'significant_fdr': reject_fdr,\n    'significant_bonf': reject_bonf\n})\n\n# Summary\nprint(f\"Original significant (p < 0.05): {(p_values < 0.05).sum()}\")\nprint(f\"Significant after FDR correction: {reject_fdr.sum()}\")\nprint(f\"Significant after Bonferroni correction: {reject_bonf.sum()}\")\n\n# Save results\nresults_df.to_csv('statistical_results.csv', index=False)\nprint(\"\u2705 Results saved to: statistical_results.csv\")\n```\n\n### Step 6: Non-Parametric Tests\n```python\n# Use when data is not normally distributed\n\n# Mann-Whitney U test (alternative to t-test)\nu_statistic, p_value_mw = mannwhitneyu(group1, group2, alternative='two-sided')\n\nprint(f\"Mann-Whitney U test:\")\nprint(f\"U-statistic: {u_statistic:.4f}\")\nprint(f\"p-value: {p_value_mw:.4e}\")\n\n# Kruskal-Wallis H test (alternative to ANOVA)\nh_statistic, p_value_kw = kruskal(*groups)\n\nprint(f\"\\nKruskal-Wallis H test:\")\nprint(f\"H-statistic: {h_statistic:.4f}\")\nprint(f\"p-value: {p_value_kw:.4e}\")\n```\n\n## Advanced Features\n\n### Normality Testing\n```python\nfrom scipy.stats import shapiro, normaltest, kstest\n\n# Test if data follows normal distribution\n\n# Shapiro-Wilk test (best for n < 5000)\nstat_sw, p_sw = shapiro(data)\nprint(f\"Shapiro-Wilk test: W={stat_sw:.4f}, p={p_sw:.4e}\")\n\n# D'Agostino-Pearson test\nstat_dp, p_dp = normaltest(data)\nprint(f\"D'Agostino-Pearson test: stat={stat_dp:.4f}, p={p_dp:.4e}\")\n\n# Interpretation\nif p_sw < 0.05:\n    print(\"\u274c Data does NOT follow normal distribution (p < 0.05)\")\n    print(\"\u2192 Recommendation: Use non-parametric tests (Mann-Whitney, Kruskal-Wallis)\")\nelse:\n    print(\"\u2705 Data appears normally distributed (p >= 0.05)\")\n    print(\"\u2192 OK to use parametric tests (t-test, ANOVA)\")\n```\n\n### Chi-Square Test for Contingency Tables\n```python\n# Test independence between categorical variables\n# contingency_table: 2D array (rows=categories1, columns=categories2)\n\n# Example: Cell type distribution across conditions\ncontingency_table = np.array([\n    [50, 30, 20],  # Condition A: T cells, B cells, NK cells\n    [40, 45, 15],  # Condition B\n    [35, 25, 40]   # Condition C\n])\n\nchi2, p_value, dof, expected = chi2_contingency(contingency_table)\n\nprint(f\"Chi-square statistic: {chi2:.4f}\")\nprint(f\"p-value: {p_value:.4e}\")\nprint(f\"Degrees of freedom: {dof}\")\nprint(f\"\\nExpected frequencies:\\n{expected}\")\n\nif p_value < 0.05:\n    print(\"\u2705 Significant association between variables (p < 0.05)\")\nelse:\n    print(\"\u274c No significant association\")\n```\n\n### Confidence Intervals\n```python\nfrom scipy.stats import t as t_dist\n\ndef calculate_confidence_interval(data, confidence=0.95):\n    \"\"\"Calculate confidence interval for mean\"\"\"\n    n = len(data)\n    mean = np.mean(data)\n    std_err = stats.sem(data)  # Standard error of mean\n\n    # t-distribution critical value\n    t_crit = t_dist.ppf((1 + confidence) \/ 2, df=n-1)\n\n    margin_error = t_crit * std_err\n    ci_lower = mean - margin_error\n    ci_upper = mean + margin_error\n\n    return mean, ci_lower, ci_upper\n\n# Usage\nmean, ci_low, ci_high = calculate_confidence_interval(data, confidence=0.95)\n\nprint(f\"Mean: {mean:.4f}\")\nprint(f\"95% CI: [{ci_low:.4f}, {ci_high:.4f}]\")\n```\n\n### Effect Size Calculation\n```python\ndef cohens_d(group1, group2):\n    \"\"\"Calculate Cohen's d effect size\"\"\"\n    n1, n2 = len(group1), len(group2)\n    var1, var2 = np.var(group1, ddof=1), np.var(group2, ddof=1)\n\n    # Pooled standard deviation\n    pooled_std = np.sqrt(((n1-1)*var1 + (n2-1)*var2) \/ (n1+n2-2))\n\n    # Cohen's d\n    d = (np.mean(group1) - np.mean(group2)) \/ pooled_std\n\n    return d\n\n# Usage\neffect_size = cohens_d(group1, group2)\nprint(f\"Cohen's d: {effect_size:.4f}\")\n\n# Interpretation\nif abs(effect_size) < 0.2:\n    print(\"Effect size: negligible\")\nelif abs(effect_size) < 0.5:\n    print(\"Effect size: small\")\nelif abs(effect_size) < 0.8:\n    print(\"Effect size: medium\")\nelse:\n    print(\"Effect size: large\")\n```\n\n## Common Use Cases\n\n### Differential Gene Expression Statistical Testing\n```python\n# Compare gene expression between two conditions\n# gene_expression_df: rows=genes, columns=samples\n# condition_labels: array indicating which condition each sample belongs to\n\nresults = []\n\nfor gene in gene_expression_df.index:\n    # Get expression values for each condition\n    cond1_expr = gene_expression_df.loc[gene, condition_labels == 'Condition1']\n    cond2_expr = gene_expression_df.loc[gene, condition_labels == 'Condition2']\n\n    # t-test\n    t_stat, p_val = ttest_ind(cond1_expr, cond2_expr)\n\n    # Log2 fold change\n    log2fc = np.log2(cond2_expr.mean() \/ cond1_expr.mean())\n\n    results.append({\n        'gene': gene,\n        'log2FC': log2fc,\n        'p_value': p_val,\n        'mean_cond1': cond1_expr.mean(),\n        'mean_cond2': cond2_expr.mean()\n    })\n\ndeg_results = pd.DataFrame(results)\n\n# Apply FDR correction\n_, deg_results['q_value'], _, _ = multipletests(\n    deg_results['p_value'],\n    alpha=0.05,\n    method='fdr_bh'\n)\n\n# Filter significant genes\nsignificant_genes = deg_results[\n    (deg_results['q_value'] < 0.05) &\n    (abs(deg_results['log2FC']) > 1)\n]\n\nprint(f\"\u2705 Identified {len(significant_genes)} differentially expressed genes\")\nprint(f\"   - Upregulated: {(significant_genes['log2FC'] > 1).sum()}\")\nprint(f\"   - Downregulated: {(significant_genes['log2FC'] < -1).sum()}\")\n\n# Save\nsignificant_genes.to_csv('deg_results.csv', index=False)\n```\n\n### Cluster Enrichment Analysis\n```python\n# Test if a cell type is enriched in a specific cluster\n# total_cells: total number of cells\n# cluster_cells: number of cells in cluster\n# celltype_total: total cells of this type\n# celltype_in_cluster: cells of this type in cluster\n\nfrom scipy.stats import fisher_exact\n\n# Create contingency table\ncontingency = [\n    [celltype_in_cluster, cluster_cells - celltype_in_cluster],  # In cluster\n    [celltype_total - celltype_in_cluster, total_cells - cluster_cells - (celltype_total - celltype_in_cluster)]  # Not in cluster\n]\n\nodds_ratio, p_value = fisher_exact(contingency, alternative='greater')\n\nprint(f\"Odds ratio: {odds_ratio:.4f}\")\nprint(f\"p-value: {p_value:.4e}\")\n\nif p_value < 0.05 and odds_ratio > 1:\n    print(f\"\u2705 Cell type is significantly ENRICHED in cluster (p < 0.05)\")\nelif p_value < 0.05 and odds_ratio < 1:\n    print(f\"\u26a0\ufe0f Cell type is significantly DEPLETED in cluster (p < 0.05)\")\nelse:\n    print(\"\u274c No significant enrichment\/depletion\")\n```\n\n### Batch Effect Detection\n```python\n# Test if there's a batch effect using ANOVA\n# gene_expression: DataFrame with genes as rows, samples as columns\n# batch_labels: array indicating batch for each sample\n\nbatch_effect_results = []\n\nfor gene in gene_expression.index:\n    # Get expression values for each batch\n    batches = [\n        gene_expression.loc[gene, batch_labels == batch]\n        for batch in np.unique(batch_labels)\n    ]\n\n    # ANOVA test\n    f_stat, p_val = f_oneway(*batches)\n\n    batch_effect_results.append({\n        'gene': gene,\n        'f_statistic': f_stat,\n        'p_value': p_val\n    })\n\nbatch_df = pd.DataFrame(batch_effect_results)\n\n# Apply FDR correction\n_, batch_df['q_value'], _, _ = multipletests(batch_df['p_value'], alpha=0.05, method='fdr_bh')\n\n# Count genes with batch effects\ngenes_with_batch_effect = (batch_df['q_value'] < 0.05).sum()\n\nprint(f\"Genes with significant batch effect: {genes_with_batch_effect} ({genes_with_batch_effect\/len(batch_df)*100:.1f}%)\")\n\nif genes_with_batch_effect > len(batch_df) * 0.1:\n    print(\"\u26a0\ufe0f WARNING: Strong batch effect detected (>10% genes affected)\")\n    print(\"\u2192 Recommendation: Apply batch correction (ComBat, Harmony, etc.)\")\nelse:\n    print(\"\u2705 Minimal batch effect\")\n```\n\n## Best Practices\n\n1. **Check Assumptions**: Always test normality before using parametric tests (t-test, ANOVA)\n2. **Multiple Testing**: Apply FDR or Bonferroni correction when testing many hypotheses\n3. **Effect Size**: Report effect sizes (Cohen's d) alongside p-values\n4. **Sample Size**: Ensure adequate sample size for statistical power\n5. **Outliers**: Check for and handle outliers appropriately\n6. **Non-Parametric Alternatives**: Use when assumptions are violated (Mann-Whitney instead of t-test)\n7. **Report Details**: Always report test used, test statistic, p-value, and correction method\n8. **Visualization**: Combine statistical tests with visualizations (box plots, violin plots)\n\n## Troubleshooting\n\n### Issue: \"Warning: p-value is very small\"\n**Solution**: This is normal for highly significant results. Report as p < 0.001 or use scientific notation\n```python\nif p_value < 0.001:\n    print(f\"p < 0.001\")\nelse:\n    print(f\"p = {p_value:.4f}\")\n```\n\n### Issue: \"Division by zero in effect size calculation\"\n**Solution**: Check for zero variance (all values identical)\n```python\nif np.std(group1) == 0 or np.std(group2) == 0:\n    print(\"Cannot calculate effect size: zero variance in one or both groups\")\nelse:\n    d = cohens_d(group1, group2)\n```\n\n### Issue: \"Test fails with NaN values\"\n**Solution**: Remove or impute NaN values before testing\n```python\n# Remove NaN\ngroup1_clean = group1[~np.isnan(group1)]\ngroup2_clean = group2[~np.isnan(group2)]\n\n# Or filter in DataFrame\ndf_clean = df.dropna(subset=['column_name'])\n```\n\n### Issue: \"Insufficient sample size warning\"\n**Solution**: Minimum sample sizes for reliable tests:\n- t-test: n \u2265 30 per group (or \u2265 5 if normally distributed)\n- ANOVA: n \u2265 20 per group\n- Correlation: n \u2265 30 total\n\n```python\nif len(group1) < 30 or len(group2) < 30:\n    print(\"\u26a0\ufe0f Warning: Small sample size. Results may not be reliable.\")\n    print(\"Consider using non-parametric tests or collecting more data.\")\n```\n\n## Technical Notes\n\n- **Libraries**: Uses `scipy.stats` and `statsmodels` (widely supported, stable)\n- **Execution**: Runs locally in the agent's sandbox\n- **Compatibility**: Works with ALL LLM providers (GPT, Gemini, Claude, DeepSeek, Qwen, etc.)\n- **Performance**: Most tests complete in milliseconds; large-scale testing (>10K genes) takes 1-5 seconds\n- **Precision**: Uses double-precision floating point (numpy default)\n- **Corrections**: FDR (Benjamini-Hochberg) recommended for genomics; Bonferroni for small numbers of tests\n\n\n## Input Validation\n\nThis skill accepts requests that match the documented purpose of `data-stats-analysis` and include enough context to complete the workflow safely.\n\nDo not continue the workflow when the request is out of scope, missing a critical input, or would require unsupported assumptions. Instead respond:\n\n> `data-stats-analysis` only handles its documented workflow. Please provide the missing required inputs or switch to a more suitable skill.\n\n## References\n- scipy.stats documentation: https:\/\/docs.scipy.org\/doc\/scipy\/reference\/stats.html\n- statsmodels documentation: https:\/\/www.statsmodels.org\/stable\/index.html\n- Multiple testing: https:\/\/www.statsmodels.org\/stable\/generated\/statsmodels.stats.multitest.multipletests.html\n- Statistical testing guide: https:\/\/docs.scipy.org\/doc\/scipy\/tutorial\/stats.html\n","use_cases":["Compare means between two groups using a t-test","Test for correlations between variables using Pearson and Spearman methods","Perform one-way ANOVA to compare means across multiple groups","Apply multiple testing corrections (FDR, Bonferroni) for statistical significance"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Data%20Analysis\/data-stats-analysis\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T11:19:32.000000Z","updated_at":"2026-11-24T07:14:40.000000Z","seo_title":"Statistical Analysis for Group Comparisons and Correlation","seo_description":"Perform t-tests, ANOVA, correlation analysis, and multiple testing corrections with Python libraries like scipy and statsmodels. This skill supports statistical testing,","seo_keywords":["t-test analysis","ANOVA test","correlation analysis","multiple testing correction","statistical hypothesis testing"]}}