科研 Skill
RCT统计检定力计算
rct-power-calculations
Calculates statistical power, minimum detectable effects, and sample sizes for RCTs, including clustering effects. Use when sizing an RCT or running a power analysis.
SKILL.md
<skill_content>
Power = 80% is conventional. Higher power (90%) is better when study is expensive or one-shot.
<mandatory_requirements>
</mandatory_requirements>
<thinking_process> When conducting power analysis:
- Specify primary outcome and effect size (MDE or expected effect)
- Choose significance level (α=0.05 typical) and desired power (0.80-0.90)
- Calculate base sample size for simple design
- Apply design effect if cluster randomization (multiply by 1+(m-1)×ICC)
- Inflate for expected non-compliance (divide by compliance²)
- Inflate for expected attrition (divide by (1-attrition_rate))
- Adjust for multiple testing if applicable
- Check feasibility; if infeasible, reduce scope or accept larger MDE </thinking_process>
<implementation_pattern>
<code_template>
@app.cell
def comprehensive_power_calculation():
# Full power calculation with all real-world adjustments
# Demonstrates compounding inflation factors for RCT sample size
import numpy as np
from scipy.stats import norm
# Parameters
alpha = 0.05
power = 0.80
mde = 0.25 # Effect size in SD units (realistic for social programs)
p = 0.50 # Treatment allocation
# Base calculation
z_alpha = norm.ppf(1 - alpha/2)
z_power = norm.ppf(power)
n_base = ((z_alpha + z_power)**2) / (p * (1-p) * mde**2)
print(f"COMPREHENSIVE POWER ANALYSIS")
print(f"=" * 60)
print(f"Parameters: α={alpha}, power={power}, MDE={mde} SD")
print(f"\n1. Base sample size: {int(np.ceil(n_base))}")
# Adjustment 1: Clustering
icc = 0.05
cluster_size = 30
design_effect = 1 + (cluster_size - 1) * icc
n_after_clustering = n_base * design_effect
print(f"\n2. Clustering adjustment:")
print(f" ICC={icc}, avg cluster size={cluster_size}")
print(f" Design effect: {design_effect:.2f}")
print(f" After clustering: {int(np.ceil(n_after_clustering))}")
# Adjustment 2: Non-compliance
compliance_rate = 0.70
n_after_compliance = n_after_clustering / (compliance_rate**2)
print(f"\n3. Non-compliance adjustment:")
print(f" Expected compliance: {compliance_rate:.0%}")
print(f" Inflation factor: {1/compliance_rate**2:.2f}")
print(f" After compliance: {int(np.ceil(n_after_compliance))}")
# Adjustment 3: Attrition
attrition_rate = 0.20
n_final = n_after_compliance / (1 - attrition_rate)
print(f"\n4. Attrition adjustment:")
print(f" Expected attrition: {attrition_rate:.0%}")
print(f" Inflation factor: {1/(1-attrition_rate):.2f}")
print(f" FINAL REQUIRED N: {int(np.ceil(n_final))}")
print(f"\n" + "=" * 60)
print(f"Total inflation: {n_final/n_base:.2f}x base sample size")
print(f"Baseline N needed: {int(np.ceil(n_final))}")
print(f"Endline N expected: {int(np.ceil(n_final * (1-attrition_rate)))}")
return int(np.ceil(n_final)),
</code_template>
</implementation_pattern>
import numpy as np
from scipy.stats import norm
alpha = 0.05
power = 0.80
mde = 0.30
# Individual randomization (baseline)
z_a = norm.ppf(1 - alpha/2)
z_p = norm.ppf(power)
n_individual = ((z_a + z_p)**2) / (0.25 * mde**2)
print(f"CLUSTER vs. INDIVIDUAL RANDOMIZATION")
print(f"=" * 60)
print(f"Individual randomization: {int(np.ceil(n_individual))} participants")
# Cluster randomization scenarios
scenarios = [
{"icc": 0.05, "cluster_size": 20},
{"icc": 0.05, "cluster_size": 50},
{"icc": 0.10, "cluster_size": 30},
{"icc": 0.20, "cluster_size": 30},
]
for scenario in scenarios:
icc = scenario["icc"]
m = scenario["cluster_size"]
de = 1 + (m - 1) * icc
n_cluster = n_individual * de
n_clusters_needed = int(np.ceil(n_cluster / m))
print(f"\nICC={icc}, cluster size={m}:")
print(f" Design effect: {de:.2f}")
print(f" Total N needed: {int(np.ceil(n_cluster))}")
print(f" Clusters needed: {n_clusters_needed}")
print(f" Inflation: {de:.2f}x individual design")
print("\nKey lesson: Higher ICC or larger clusters → much larger N needed")
return ()
</code>
<lesson>
Design effect = 1 + (m-1) × ICC. With ICC=0.10 and m=30, DE=3.9, meaning you need 4x the individual-randomized sample size. Cluster randomization trades power for validity when spillovers are a concern.
</lesson>
</example>
</examples>
<common_mistakes>
<mistake severity="critical">
<what>Conducting power analysis after data collection (post-hoc power)</what>
<consequence>Meaningless exercise, doesn't inform anything, misinterpreted as evidence quality</consequence>
<prevention>Power analysis is for design phase only. Never calculate "observed power" after study</prevention>
</mistake>
<mistake severity="critical">
<what>Ignoring clustering design effect in sample size calculation</what>
<consequence>Study underpowered by 2-4x, fails to detect real effects despite large nominal sample</consequence>
<prevention>ALWAYS multiply by design effect DE = 1+(m-1)×ICC for cluster randomization</prevention>
</mistake>
<mistake severity="high">
<what>Using overoptimistic effect size assumptions</what>
<consequence>Study designed to detect implausibly large effects, fails for realistic effects</consequence>
<prevention>Use conservative estimates from pilots, literature, or smallest policy-relevant effect</prevention>
</mistake>
<mistake severity="high">
<what>Not inflating for attrition and non-compliance</what>
<consequence>Final analysis underpowered even if enrollment meets naive target</consequence>
<prevention>Always inflate for expected attrition (÷ (1-attrition_rate)) and compliance (÷ compliance²)</prevention>
</mistake>
<mistake severity="medium">
<what>Treating power as binary threshold (80% good, 79% bad)</what>
<consequence>Arbitrary decisions, missing that power is continuous and context-dependent</consequence>
<prevention>Power is a continuum. Consider costs, effect importance, and Type I vs. II error tradeoffs</prevention>
</mistake>
</common_mistakes>
<interpretation_guide>
<sample_size_rules_of_thumb>
For 80% power, α=0.05, 50/50 allocation:
- MDE = 0.10 SD: ~3,140 total
- MDE = 0.20 SD: ~786 total
- MDE = 0.30 SD: ~350 total
- MDE = 0.40 SD: ~198 total
- MDE = 0.50 SD: ~128 total
Then multiply by:
- Design effect if clustering: 1+(m-1)×ICC
- 1/compliance² for non-compliance
- 1/(1-attrition_rate) for attrition
</sample_size_rules_of_thumb>
<when_study_is_underpowered>
If power calculation shows infeasible N:
- Increase MDE (accept detecting only larger effects)
- Reduce scope (fewer outcomes, simpler design)
- Improve efficiency (stratification, ANCOVA with baseline)
- Pool with other studies (consortium approach)
- Use alternative design (regression discontinuity, DID)
- Accept higher Type II error risk (document explicitly)
Do NOT: proceed with underpowered study and hope for best.
</when_study_is_underpowered>
</interpretation_guide>
<references>
<paper>Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences. 2nd ed. Erlbaum.</paper>
<paper>Duflo, E., Glennerster, R., & Kremer, M. (2007). Using randomization in development economics research. Handbook of Development Economics, 4, 3895-3962.</paper>
<paper>Donner, A., & Klar, N. (2000). Design and Analysis of Cluster Randomization Trials in Health Research. Arnold Publishers.</paper>
<paper>Hoenig, J. M., & Heisey, D. M. (2001). The abuse of power: The pervasive fallacy of power calculations for data analysis. American Statistician, 55(1), 19-24.</paper>
<paper>Vivalt, E. (2020). How much can we generalize from impact evaluations? Journal of the European Economic Association, 18(6), 3045-3089.</paper>
</references>
</skill_content>
示例提示词
我想计算这个集群随机实验所需的样本量和最小可侦测效应。
所属插件
安装该插件会一并获得同领域的 58 个 Skill / MCP。
同插件的其他科研 Skill
- Mesa社会主体建模Builds Mesa agent-based models of opinion dynamics, segregation, social contagion, and network diffusion. Use when simulating emergent social behavior from agent rules.
- Mesa3主体建模引擎Builds agent-based models with the Mesa 3 AgentSet API, cell spaces, and batch_run sweeps for segregation, diffusion, and cooperation. Use for a Mesa 3.x ABM build or debug.
- 观察数据因果推断Estimates causal effects with DiD, IV, RDD, panel fixed effects, and propensity scores via statsmodels, linearmodels, DoWhy, and EconML. Use for observational or quasi-experimental causal estimation.
- 效应量元分析Pools effect sizes across studies with fixed/random-effects models, heterogeneity stats, forest/funnel plots, and publication-bias tests. Use for a systematic review’s quantitative synthesis.
- 缺失数据插补处理Handles missing data by naming the MCAR/MAR/MNAR mechanism, then applying multiple imputation (MICE) or FIML instead of single imputation. Use when a dataset has missing values to treat.
- 多层线性混合模型Fits mixed-effects/multilevel models (random slopes, ICC, GLMMs) for nested or longitudinal data via statsmodels, bambi, or R lme4/brms. Use for grouped data with within- vs between-cluster questions.
- 定性比较分析QCARuns crisp-, multi-value, and fuzzy-set Qualitative Comparative Analysis via R’s QCA package. Use for configurational or necessary/sufficient-condition research.
- 质性编码与主题分析Builds codebooks and computes intercoder reliability (Krippendorff’s alpha, kappa) for thematic or content coding, including human-vs-LLM double coding. Use when coding text or reporting reliability.
- 社会网络结构分析Computes network centrality, community detection, and ERGM inferential models matched to the research question via networkx/igraph. Use for social-network analysis beyond basic visualization.
- 社科研究设计把关Routes a study to its research design (experiment, quasi-experiment, observational, qualitative) and pins the identifying assumption first. Use when choosing a study design.
- 社科推论结论审核Audits inferential claims against the design before publication: unwarranted causal language, p-value/CI misreadings, and multiple-comparison issues. Use when checking a results section.
- 量表测量质量把关Checks that a scale’s reliability, validity, and measurement invariance are established before trusting or comparing it across groups. Use when adopting or reporting a survey instrument.
- 社科研究流程总控Coordinates a study through design, measurement, sampling, analysis, and inference gates with a shared Design Passport. Use for an end-to-end methodology review of a whole study.
- 质性研究可信度把关Gates qualitative trustworthiness before write-up: positionality, credibility, transferability, dependability, confirmability per Lincoln and Guba. Use before writing ethnographic findings.
- 抽样方法与样本量把关Checks that the sampling frame, method, and size match the inference paradigm before data collection. Use when planning recruitment or judging sample generalization.
- 复杂抽样调查分析Analyzes complex-sample survey data with design-based inference: weights, strata, PSUs, and calibration via Python svy or R survey/srvyr. Use for weighted surveys like GSS, ANES, or DHS.
- 文本数据定量分析Analyzes text as social-science data with topic modeling, embeddings, and validated dictionary or classification methods. Use for computational text analysis beyond a keyword count.
- 政策议题框架分析Runs anthropological framing and metaphor analysis on contested-policy documents, producing actor-attributed CSVs for NVivo import. Use for policy-framing or metaphor-analysis coding.
- 跨国比较政治分析Merges QoG, Polity5, and Freedom House data and runs cross-sectional OLS with fixed effects and regime classification. Use for comparative political-institution research.
- 计算社会学方法Covers social-media data collection, bot detection, network homophily, echo-chamber analysis, and conjoint survey experiments. Use for large-scale digital-trace sociology research.
- 冲突事件数据分析Downloads ACLED/UCDP conflict data and runs spatio-temporal clustering, conflict-onset logit panels, and fatality estimation. Use for quantitative armed-conflict research.
- 联合分析调查实验Designs conjoint survey experiments and estimates AMCEs via OLS, marginal means, and respondent-level heterogeneity. Use when designing or analyzing a choice-based conjoint experiment.
- 统计方法教学规范Defines the baseline statistical teaching and reproducibility standards shared across this analysis skill family. Use as the methodology reference other skills in the family build on.
- 人口统计方法分析Computes life tables, Leslie-matrix population projections, Lee-Carter mortality forecasts, and Kitagawa decomposition. Use for formal demographic analysis of mortality or population structure.
常见问题
RCT统计检定力计算能做什么?
Calculates statistical power, minimum detectable effects, and sample sizes for RCTs, including clustering effects. Use when sizing an RCT or running a power analysis。
如何安装RCT统计检定力计算?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「RCT统计检定力计算」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
RCT统计检定力计算需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
RCT统计检定力计算经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。