科研 Skill
RCT随机分配实现
rct-randomization
Implements RCT randomization: stratification, blocking, cluster randomization, and balance/misfit handling. Use when assigning or checking treatment-arm balance in an RCT.
SKILL.md
<skill_content>
Randomization must be reproducible, documented, and executed exactly once per study.
<mandatory_requirements>
</mandatory_requirements>
<thinking_process> When implementing randomization:
- Define eligible sample BEFORE randomization
- Choose randomization method (simple/permutation/stratified/cluster)
- Set random seed ONCE, document seed value
- Generate assignments (never re-run)
- Save assignments to persistent storage immediately
- Create backup of assignments
- Check balance (but don't re-randomize if unbalanced)
- Document any implementation deviations </thinking_process>
<implementation_pattern>
<code_template>
@app.cell
def randomize_trial():
# Permutation randomization with stratification
# CRITICAL: Set seed ONCE, save immediately, NEVER re-run
import numpy as np
import pandas as pd
from datetime import datetime
# Set seed ONCE at beginning (DOCUMENT THIS VALUE)
RANDOM_SEED = 42
np.random.seed(RANDOM_SEED)
# Load eligible sample
df = pd.read_csv("/mnt/data/eligible_units.csv")
n = len(df)
print(f"RANDOMIZATION PROTOCOL")
print(f"Date: {datetime.now()}")
print(f"Random seed: {RANDOM_SEED}")
print(f"Sample size: {n}")
# Stratified permutation randomization
treatment_prop = 0.5
strata_var = 'baseline_risk' # Strong outcome predictor
df['treatment'] = 0
for stratum in df[strata_var].unique():
strata_mask = df[strata_var] == stratum
n_strata = strata_mask.sum()
n_treat = int(n_strata * treatment_prop)
# Permutation within stratum
assignments = np.concatenate([
np.ones(n_treat, dtype=int),
np.zeros(n_strata - n_treat, dtype=int)
])
np.random.shuffle(assignments)
df.loc[strata_mask, 'treatment'] = assignments
# CRITICAL: Save immediately (NEVER re-run randomization)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
df.to_csv(f"/mnt/data/randomization_assignments_{timestamp}.csv", index=False)
# Create backup
df.to_csv(f"/mnt/data/randomization_assignments_BACKUP.csv", index=False)
print(f"\nAssignments saved to:")
print(f" /mnt/data/randomization_assignments_{timestamp}.csv")
print(f"Treatment: {df['treatment'].sum()} ({df['treatment'].mean():.1%})")
print(f"Control: {(~df['treatment'].astype(bool)).sum()} ({(~df['treatment'].astype(bool)).mean():.1%})")
return df,
</code_template>
</implementation_pattern>
import numpy as np
import pandas as pd
# CRITICAL: Set seed once
np.random.seed(123)
# Identify clusters
clusters = df['village_id'].unique()
n_clusters = len(clusters)
n_treat_clusters = int(n_clusters * 0.5)
print(f"CLUSTER RANDOMIZATION")
print(f"Total clusters: {n_clusters}")
print(f"Treatment clusters: {n_treat_clusters}")
# Permutation at cluster level
cluster_assignments = np.concatenate([
np.ones(n_treat_clusters, dtype=int),
np.zeros(n_clusters - n_treat_clusters, dtype=int)
])
np.random.shuffle(cluster_assignments)
# Map cluster assignments to individuals
cluster_map = dict(zip(clusters, cluster_assignments))
df['treatment'] = df['village_id'].map(cluster_map)
# Report
print(f"\nIndividuals in treatment: {df['treatment'].sum()}")
print(f"Individuals in control: {(~df['treatment'].astype(bool)).sum()}")
# Calculate design effect
avg_cluster_size = df.groupby('village_id').size().mean()
icc = 0.05 # Assumed intra-cluster correlation
design_effect = 1 + (avg_cluster_size - 1) * icc
print(f"\nAverage cluster size: {avg_cluster_size:.1f}")
print(f"Assumed ICC: {icc:.3f}")
print(f"Design effect: {design_effect:.2f}")
print(f"Effective sample size: {len(df)/design_effect:.0f}")
return df,
</code>
<lesson>
Cluster randomization trades power for validity. Design effect = 1 + (m-1) × ICC where m is cluster size and ICC is intra-cluster correlation. Higher ICC or larger clusters → larger design effect → greater power loss. But necessary when spillovers would contaminate individual randomization.
</lesson>
</example>
</examples>
<common_mistakes>
<mistake severity="critical">
<what>Re-running randomization to get "better" balance</what>
<consequence>Invalidates randomization inference, creates selection bias, corrupts p-values</consequence>
<prevention>Run ONCE, save immediately, accept whatever balance you get. If deeply concerned about imbalance, use stratification or re-randomization with proper adjustment (difficult)</prevention>
</mistake>
<mistake severity="critical">
<what>Setting random seed multiple times in randomization code</what>
<consequence>Compromises randomness, makes sequence non-random, creates reproducibility issues</consequence>
<prevention>Set seed ONCE at very beginning, never call np.random.seed() again in randomization code</prevention>
</mistake>
<mistake severity="high">
<what>Using simple randomization when sample size is known</what>
<consequence>Sampling variation creates unbalanced groups, power loss, difficult to explain discrepancies</consequence>
<prevention>Use permutation randomization (shuffle fixed number of 1s and 0s) when N is known</prevention>
</mistake>
<mistake severity="high">
<what>Not stratifying when strong predictors available</what>
<consequence>Unnecessary power loss, imbalanced groups on important characteristics</consequence>
<prevention>Stratify on 1-3 strong outcome predictors to improve precision</prevention>
</mistake>
<mistake severity="medium">
<what>Not documenting randomization seed and procedure</what>
<consequence>Non-reproducible, inability to verify implementation, suspicion of manipulation</consequence>
<prevention>Document seed, date, time, code version, sample characteristics in protocol</prevention>
</mistake>
</common_mistakes>
<interpretation_guide>
<balance_check_interpretation>
After randomization (but NOT as reason to re-randomize):
- Normalized diff |d| < 0.1: Excellent balance
- 0.1 ≤ |d| < 0.25: Acceptable balance
- |d| ≥ 0.25: Imbalanced on this variable (include as control, but don't re-randomize)
- Joint F-test p > 0.10: Overall balance adequate
- Joint F-test p < 0.05: Some imbalance (expected 5% of time by chance)
Never re-randomize based on balance. If you must, use proper re-randomization protocol with inference adjustment (complex).
</balance_check_interpretation>
<when_to_use_each_method>
- **Simple randomization**: Sequential enrollment, N unknown at randomization
- **Permutation**: N known, want exact allocation ratio
- **Stratified**: Strong baseline predictors available, want precision gains
- **Cluster**: Spillovers likely within clusters (social, geographic)
- **Re-randomization**: Advanced method requiring special inference (seek expert help)
</when_to_use_each_method>
</interpretation_guide>
<references>
<paper>Bruhn, M., & McKenzie, D. (2009). In pursuit of balance: Randomization in practice in development field experiments. American Economic Journal: Applied Economics, 1(4), 200-232.</paper>
<paper>Athey, S., & Imbens, G. W. (2017). The econometrics of randomized experiments. Handbook of Economic Field Experiments, 1, 73-140.</paper>
<paper>Duflo, E., Glennerster, R., & Kremer, M. (2007). Using randomization in development economics research. Handbook of Development Economics, 4, 3895-3962.</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随机分配实现能做什么?
Implements RCT randomization: stratification, blocking, cluster randomization, and balance/misfit handling. Use when assigning or checking treatment-arm balance in an RCT。
如何安装RCT随机分配实现?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「RCT随机分配实现」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
RCT随机分配实现需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
RCT随机分配实现经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。