Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Clean, recode, and prepare survey response data for analysis
.claude/skills/brycewang-stanford-survey-data-processing/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 22% | 0% |
| case-08 | ✓→✗ | ▼ Worse | 88% | 0% |
| case-09 | ✓→✓ | = Same ✓ | 56% | 0% |
| case-10 | ✓→✓ | = Same ✓ | 65% | 0% |
| case-02 | ✓→✓ | = Same ✓ | 96% | 0% |
A skill for cleaning, recoding, and preparing survey response data for statistical analysis. Covers handling common survey data issues such as incomplete responses, attention check failures, reverse-coded items, scale construction, open-ended response coding, and export to analysis-ready formats compatible with SPSS, Stata, and R.
Survey data from platforms like Qualtrics, SurveyMonkey, REDCap, and Google Forms each have their own export formats and quirks. The first step is always standardization.
pythonimport pandas as pd import numpy as np def assess_survey_quality(df, duration_col="duration_seconds", min_duration=60): """ Generate a survey data quality report. Checks: - Completion rates per question - Response duration (speeders and slow responders) - Straight-line responding patterns - Attention check failures """ report = {} # Overall completion total_respondents = len(df) complete = df.dropna(thresh=int(len(df.columns) * 0.8)) report["total_responses"] = total_respondents report["substantially_complete"] = len(complete) report["completion_rate"] = f"{len(complete)/total_respondents*100:.1f}%" # Duration analysis if duration_col in df.columns: durations = df[duration_col].dropna() report["median_duration_seconds"] = durations.median() report["speeders"] = (durations < min_duration).sum() report["speeder_pct"] = f"{(durations < min_duration).mean()*100:.1f}%" # Missing data per question missing_by_col = df.isna().sum().sort_values(ascending=False) report["most_skipped_questions"] = missing_by_col.head(10).to_dict() return report
pythondef detect_straightlining(df, likert_columns, threshold=0.9): """ Detect respondents who select the same answer for nearly all Likert-scale questions (straight-line responding). A respondent is flagged if the proportion of their most common response exceeds the threshold. """ flagged = [] for idx, row in df[likert_columns].iterrows(): responses = row.dropna() if len(responses) == 0: continue most_common_pct = responses.value_counts().iloc[0] / len(responses) if most_common_pct >= threshold: flagged.append(idx) return flagged def check_attention_items(df, attention_checks): """ Validate attention check (trap) questions. Args: attention_checks: dict of {column_name: correct_answer} Example: {"q15_attention": 4, "q32_trap": "strongly agree"} """ failed = pd.Series(False, index=df.index) for col, correct in attention_checks.items(): failed = failed | (df[col] != correct) return df.index[failed].tolist()
Many validated psychological scales include reverse-coded items to detect acquiescence bias. These must be recoded before computing scale scores.
pythondef reverse_code(df, columns, scale_max, scale_min=1): """ Reverse-code specified columns for Likert-type scales. Formula: reversed = (scale_max + scale_min) - original Example for a 1-5 scale: 1 -> 5, 2 -> 4, 3 -> 3, 4 -> 2, 5 -> 1 """ df_recoded = df.copy() for col in columns: df_recoded[col] = (scale_max + scale_min) - df[col] return df_recoded # Example usage with a Big Five personality scale reverse_items = { "extraversion": ["ext_2", "ext_4", "ext_6"], "neuroticism": ["neur_1", "neur_3", "neur_5"], "agreeableness": ["agree_3", "agree_5"], } # For a 1-7 Likert scale: for construct, items in reverse_items.items(): df = reverse_code(df, items, scale_max=7, scale_min=1)
pythondef compute_scale_scores(df, scale_definitions, method="mean"): """ Compute composite scale scores from individual items. Args: scale_definitions: dict mapping scale name to list of columns method: "mean" or "sum" Returns: DataFrame with new scale score columns """ for scale_name, items in scale_definitions.items(): if method == "mean": df[scale_name] = df[items].mean(axis=1) elif method == "sum": df[scale_name] = df[items].sum(axis=1) # Also compute Cronbach's alpha for reliability alpha = cronbachs_alpha(df[items]) print(f"{scale_name}: alpha = {alpha:.3f} " f"(n_items = {len(items)})") return df def cronbachs_alpha(item_df): """ Compute Cronbach's alpha for internal consistency reliability. Values above 0.70 are generally considered acceptable. """ item_df = item_df.dropna() n_items = item_df.shape[1] if n_items < 2: return np.nan item_variances = item_df.var(axis=0, ddof=1) total_variance = item_df.sum(axis=1).var(ddof=1) alpha = (n_items / (n_items - 1)) * ( 1 - item_variances.sum() / total_variance ) return alpha
pythondef code_open_responses(df, text_column, codebook): """ Apply a predefined codebook to open-ended responses using keyword matching. For research-quality coding, this should be supplemented with manual coding by trained raters. Args: codebook: dict mapping code names to keyword lists Example: { "financial_concern": ["money", "cost", "expensive", "afford"], "time_constraint": ["time", "busy", "schedule", "hours"], "quality_issue": ["quality", "broken", "defect", "poor"], } """ for code_name, keywords in codebook.items(): pattern = "|".join(keywords) df[f"code_{code_name}"] = ( df[text_column] .str.lower() .str.contains(pattern, na=False) .astype(int) ) return df
When multiple coders classify open-ended responses:
Cohen's Kappa (2 raters):
- < 0.20: poor agreement
- 0.21-0.40: fair
- 0.41-0.60: moderate
- 0.61-0.80: substantial
- 0.81-1.00: almost perfect
Fleiss' Kappa (3+ raters):
- Same interpretation scale as Cohen's
- Use when more than two raters code the same responses
Process:
1. Develop codebook with definitions and examples
2. Train coders on 10-20 practice responses
3. Code 20% of responses independently (overlap set)
4. Calculate inter-rater reliability on the overlap set
5. If kappa < 0.70, discuss disagreements and refine codebook
6. Repeat until acceptable reliability is achieved
7. Divide remaining responses among codersSurvey data is typically exported in wide format (one row per respondent, one column per question). Many analyses require long format.
pythondef reshape_repeated_measures(df, id_col, time_points, measure_prefix): """ Reshape repeated-measures survey data from wide to long. Example: columns q1_pre, q1_post -> long format with time column ("pre", "post") and value column. """ value_vars = [f"{measure_prefix}_{t}" for t in time_points] long_df = pd.melt( df, id_vars=[id_col], value_vars=value_vars, var_name="time_point", value_name=measure_prefix ) # Clean time_point column long_df["time_point"] = ( long_df["time_point"] .str.replace(f"{measure_prefix}_", "") ) return long_df
Export formats by software:
SPSS (.sav):
- Use pyreadstat: pyreadstat.write_sav(df, "output.sav")
- Include variable labels and value labels
- Set measurement level (nominal, ordinal, scale)
Stata (.dta):
- Use pandas: df.to_stata("output.dta")
- Include variable labels via write_stata with labels dict
R (.csv with codebook):
- Export CSV plus a separate codebook document
- Or use pyreadstat to write .rds format
- Include factor level definitions
General best practices:
- Include a unique respondent ID column
- Use numeric codes for categorical variables (with labels)
- Document all recoding in a companion codebook
- Save both raw and processed versions
- Include a timestamp column for data versioningProper survey data processing is essential for valid statistical inference. Decisions made during cleaning and recoding directly affect research conclusions, making transparent documentation of every step a methodological requirement rather than a convenience.
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-09 | pass→pass | 16,509 | 12,573 | -24% | 1 | 1 | 0% | 2,962 | 4,615 | +56% | 0 | 0 | — |
case-10 | pass→pass | 18,387 | 15,166 | -18% | 1 | 1 | 0% | 2,959 | 4,894 | +65% | 0 | 0 | — |
case-01 | fail→pass | 23,628 | 35,928 | +52% | 1 | 1 | 0% | 4,843 | 5,908 | +22% | 0 | 0 | — |
case-02 | pass→pass | 10,843 | 10,351 | -5% | 1 | 1 | 0% | 2,226 | 4,369 | +96% | 0 | 0 | — |
case-03 | pass→pass | 10,254 | 9,658 | -6% | 1 | 1 | 0% | 2,051 | 4,012 | +96% | 0 | 0 | — |
case-04 | pass→pass | 12,052 | 14,692 | +22% | 1 | 1 | 0% | 2,358 | 5,286 | +124% | 0 | 0 | — |
case-05 | pass→pass | 16,186 | 14,098 | -13% | 1 | 1 | 0% | 3,267 | 5,363 | +64% | 0 | 0 | — |
case-06 | pass→pass | 16,822 | 26,426 | +57% | 1 | 1 | 0% | 3,171 | 7,504 | +137% | 0 | 0 | — |
case-07 | pass→pass | 10,859 | 10,662 | -2% | 1 | 1 | 0% | 1,935 | 4,440 | +129% | 0 | 0 | — |
case-08 | pass→fail | 12,883 | 11,392 | -12% | 1 | 1 | 0% | 2,394 | 4,490 | +88% | 0 | 0 | — |
case-11 | pass→pass | 10,356 | 7,093 | -32% | 1 | 1 | 0% | 1,649 | 3,825 | +132% | 0 | 0 | — |
case-12 | pass→pass | 16,706 | 10,420 | -38% | 1 | 1 | 0% | 2,370 | 4,255 | +80% | 0 | 0 | — |
case-13 | pass→pass | 8,526 | 9,118 | +7% | 1 | 1 | 0% | 1,554 | 3,749 | +141% | 0 | 0 | — |
case-14 | pass→pass | 14,036 | 11,105 | -21% | 1 | 1 | 0% | 3,067 | 4,725 | +54% | 0 | 0 | — |
case-15 | fail→fail | 16,969 | 16,763 | -1% | 1 | 1 | 0% | 2,582 | 5,375 | +108% | 0 | 0 | — |
case-16 | fail→fail | 20,543 | 14,717 | -28% | 1 | 1 | 0% | 3,337 | 4,846 | +45% | 0 | 0 | — |
case-17 | pass→pass | 15,559 | 10,360 | -33% | 1 | 1 | 0% | 3,205 | 4,541 | +42% | 0 | 0 | — |
case-18 | pass→pass | 11,743 | 8,371 | -29% | 1 | 1 | 0% | 2,140 | 3,994 | +87% | 0 | 0 | — |
case-19 | pass→pass | 6,970 | 6,354 | -9% | 1 | 1 | 0% | 1,369 | 3,801 | +178% | 0 | 0 | — |
case-20 | pass→pass | 11,269 | 11,896 | +6% | 1 | 1 | 0% | 1,967 | 4,189 | +113% | 0 | 0 | — |
case-21 | fail→fail | 25,505 | 25,538 | +0% | 1 | 1 | 0% | 4,960 | 7,412 | +49% | 0 | 0 | — |
case-22 | fail→fail | 14,884 | 15,504 | +4% | 1 | 1 | 0% | 2,852 | 5,439 | +91% | 0 | 0 | — |
case-23 | fail→fail | 12,785 | 12,612 | -1% | 1 | 1 | 0% | 2,225 | 4,594 | +106% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of 0 percentage points is the difference between those two pass rates over the 23 comparable cases. 1 case got worse with the skill loaded, and it is included in that figure.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.