Home/Blog/Survey Data Cleaning: How to Clean Survey Data Before Analysis
Back to Blog

Survey Data Cleaning: How to Clean Survey Data Before Analysis

May 30, 2026
24 min read
By DSTechnoverse
Survey Research

A step-by-step survey data cleaning checklist: protect the raw file, fix IDs and duplicates, run range and skip logic checks, treat missing values and outliers, and document every change in Stata, R, SPSS or Excel.

Survey Data Cleaning: How to Clean Survey Data Before Analysis

Quick answer: Survey data cleaning is the scripted process of turning a raw survey export into an analysis-ready file: protect the raw data, check IDs and duplicates, apply respondent-level quality rules, run range, consistency and skip logic checks, declare and treat missing values, investigate outliers, recode and derive variables, and record every change in a cleaning log. Do it in Stata, R or SPSS syntax rather than by hand, so anyone can rebuild the clean file from the raw one.

Survey data cleaning is the step that decides whether your results mean anything. Analysts have a saying: garbage in, garbage out. No statistical test can rescue a dataset where "don't know" is coded 99 and averaged as income, where the same household appears twice, or where half the respondents answered questions they should have skipped.

This guide is a practical answer to "how to clean survey data" for household, baseline, CSR, customer and thesis surveys. It gives you a data cleaning checklist you can adapt, explains how to handle missing values and outliers, shows how skip logic checks work, and maps each step to Stata, R, SPSS and Excel. It assumes the data has already been collected. Quality control during fieldwork (back-checks, GPS and audio audits, daily enumerator monitoring) is a separate discipline covered in data quality control in large-scale surveys, and the choice of collection mode is covered in CATI vs CAPI vs paper surveys. If your data is a sensor time series rather than a questionnaire, the logic is different again; see cleaning air quality monitoring data.

What Survey Data Cleaning Is, and What It Is Not

Three activities are often lumped together, and confusing them causes both gaps and duplicated effort.

ActivityWhen it happensMain questionTypical output
Field quality controlDuring data collectionIs the interview real and correctly conducted?Back-check reports, enumerator flags, re-visits
Survey data cleaningAfter export, before analysisIs each value valid, consistent and correctly coded?Clean dataset, cleaning script, cleaning log
Data screeningAfter cleaning, before testingDo the data meet the assumptions of the planned analysis?Normality, multicollinearity and distribution checks

Field QC is the cheapest place to fix problems, because the enumerator can still go back to the household. Cleaning catches what slipped through and makes the file internally coherent. Screening then tells you which analysis is appropriate, which is the subject of choosing the right statistical test.

Cleaning is not "making the data look right". Every change needs a rule written before you see its effect, and the original value must survive in the raw file.

The Survey Data Cleaning Checklist

Use this as the spine of your cleaning script. The order matters: you cannot judge outliers before missing codes are declared, and you cannot check skip logic before you know which records are genuine.

StepTaskKey checks
1Protect the raw fileRead-only archive, version naming, project folders
2Import and check structureVariable types, encoding, labels, dates, leading zeros
3Identifiers and duplicatesUnique ID, exact and near duplicates, roster linkage
4Respondent-level qualityConsent, partials, speeders, straight-liners, attention checks
5Range and consistencyValid ranges, logical combinations, units
6Skip logic checksAnswered when it should be skipped, blank when it should be answered
7Missing valuesDeclare codes, diagnose mechanism, choose treatment
8OutliersDetect, investigate, decide, document
9Recode and deriveOther-specify, reverse coding, scales, indices
10Weights and final verificationStrata, clusters, weights, reconciliation counts
11DocumentCleaning log, script, clean file, codebook
The survey data cleaning workflow

Step 1: Protect the Raw File

Before changing anything, archive the raw export exactly as it came from the server or data entry system. Make it read-only. Every later file should be produced by a script that reads the raw file, never by editing a copy and saving over it.

Keep separate folders for raw exports (with download dates in the file names), numbered scripts, versioned clean files and documentation. If data arrives in batches during fieldwork, re-run the whole script on the combined file; manual batch-by-batch edits get lost when a later export overwrites them.

Step 2: Import Correctly and Check Structure

Many cleaning problems are created at import. Check these before anything else.

  • Variable types. Numeric codes read as text will not range-check or sort properly. Text read as numbers loses leading zeros, which destroys census codes, PIN codes and phone numbers.
  • Dates and times. Mixed day-month and month-day formats corrupt any duration or age calculation. Excel will silently convert some codes into dates.
  • Encoding. Open-ended answers in Indian scripts need UTF-8 handling.
  • Labels. Exports from ODK, KoboToolbox or SurveyCTO can come with labels or with raw choice names. Decide which you want and attach value labels from the form definition, not by hand.
  • Multiple-select questions. These usually arrive as one text field with space-separated choices plus one binary column per choice. Confirm the binary columns match the text field.

Then compare record counts with the field tracker and summarise every variable. In Stata that is describe, codebook and inspect; in R, str, summary and skimr::skim; in SPSS, Display Dictionary and FREQUENCIES. The minimum and maximum of every numeric variable is the single most useful output you will generate all week.

Step 3: Identifiers and Duplicates

Every record needs a unique identifier, and you should prove it is unique rather than assume it. In Stata, isid household_id stops the script if the ID repeats; in R, a count of IDs appearing more than once should return zero rows.

Duplicates come in several forms:

TypeHow it arisesHow to detectUsual resolution
Exact duplicateForm submitted twice from the deviceAll variables identicalKeep one, log the other
Same ID, different dataRe-interview, ID typed wrongly, two enumeratorsDuplicate ID with differing answersCheck with field team, re-assign or drop
Same household, different IDHousehold interviewed twice under new IDsMatching name, phone, GPS or rosterInvestigate, keep the verified record

Roster data (household members, plots, livestock, loans) sits in separate repeat-group files. After cleaning the household file, merge each roster to it and check that every child row has a parent and that counts agree, for example that the number of members in the roster equals the household size question.

Never resolve "same ID, different data" by automatically keeping the latest submission; ask the field team, then record the decision.

Step 4: Respondent-Level Quality Rules

Dropping a respondent is a serious act, so the criteria should be written down before you look at the results and applied mechanically. These checks earn their place in almost every survey.

CheckRule of thumbWhat it catches
ConsentConsent variable not "yes"Records that should not be analysed at all
SpeedingCompletion under one third of the median timeClicked through without reading
Straight-liningSame answer for every item in a grid of 8+Disengaged respondent
Attention check failureAn item that instructs "select Agree"Bots and inattentive panels
Impossible combinationsAge 19 with 25 years of work experienceData entry or comprehension error
Duplicate submissionsSame device, same responses, minutes apartRepeat entry, intentional or not
Excessive item non-responseMore than 40% of key items blankPartial completion

Thresholds such as "one third of the median" are conventions; set the cut-off after looking at the duration distribution. An enumerator whose interviews are consistently far shorter than everyone else's is a fieldwork problem, as are GPS and audio mismatches, and the right response is the back-check protocol in data quality control in large-scale surveys, not a silent deletion at the cleaning stage.

Report your exclusions with counts. "We removed 47 of 1,240 responses: 22 for speeding, 14 for straight-lining, 11 for failed attention checks" is transparent. Silently ending up with 1,193 is not.

Step 5: Range and Consistency Checks

Range checks confirm that every value is possible: no age of 200, no Likert answer of 9 on a five-point scale, no negative land area. Consistency checks confirm that values make sense together.

Check typeExample ruleTypical cause when it fails
Hard rangeAge between 0 and 110Typing error, missing code not declared
Soft rangeMonthly household income above 10 times the medianGenuine extreme or unit error
Cross-variable logicRespondent's age greater than eldest child's age plus 12Wrong member selected, wrong age
Sum checksLand owned plus land leased in equals land operatedPartial answers, unit mix-up
Time consistencyInterview date within fieldwork windowDevice clock set wrongly
Roster consistencyHousehold size equals number of roster membersMembers added or dropped in the roster

Hard-range failures are usually set to missing or corrected from the paper record or audio. Soft-range failures are flagged for investigation, not changed automatically. Unit problems deserve special care in Indian rural surveys: a bigha differs by state and sometimes by district, so the conversion factor must come from the study area, and the original unit should be kept as a separate variable.

Constraints in ODK, KoboToolbox or SurveyCTO forms reduce these errors but do not remove the need for checks, because forms change mid-survey and cross-module logic is rarely fully coded.

Step 6: Skip Logic Checks

Skip logic checks test whether each question was answered by exactly the respondents who should have answered it. Two errors are possible:

  • Answered when it should have been skipped. A respondent who said "no" to owning livestock has values for milk sales.
  • Blank when it should have been answered. A respondent who said "yes" to taking a loan has no loan amount.

Write each rule from the questionnaire's routing and test both directions. CAPI relevance conditions usually prevent the first error, but older submissions may follow an earlier form version. With paper surveys both errors are common.

Illustrative rules for a livelihoods module:

Filter questionDependent questionsCheck
Q20 Owns livestock (1 yes, 2 no)Q21 to Q25 livestock numbers and salesIf Q20 = 2, Q21 to Q25 must be blank or coded "not applicable"
Q30 Took a loan in last 12 monthsQ31 source, Q32 amount, Q33 purposeIf Q30 = 1, Q31 to Q33 must not be blank
Q40 Any member migrated for workMigrant rosterIf Q40 = 2, roster must have zero rows for that household

Values that should have been skipped are normally set to "not applicable", after checking the filter answer itself is not the error. Blanks that should have been answered are genuine missing values.

Keep "not applicable" distinct from "missing". A blank loan amount for a household that took no loan is not missing data, and treating it as missing will distort any analysis of missingness. Good questionnaire design makes this much easier; see how to design a baseline survey questionnaire.

Step 7: Missing Values in Survey Data

Before treating missing values, declare them. Surveys use special codes such as 98 for "don't know", 99 for "refused" and 97 for "not applicable", and these must be declared as missing (or as their own categories) rather than analysed as numbers. A "don't know" coded 99 and left undeclared will inflate every mean in the dataset. In Stata use mvdecode or extended missing values such as .d and .r; in SPSS use the MISSING VALUES command; in R convert the codes to NA, keeping a separate variable for the reason if you need it.

Then diagnose the mechanism. The percentage missing matters far less than why it is missing.

MCAR, missing completely at random. A tablet crashed, a page was skipped by accident. The missingness is unrelated to anything. Simple deletion is defensible.

MAR, missing at random. Missingness depends on something you observed. Older respondents skipped the online banking question more often. You can model and impute it because the predictor is in your data.

MNAR, missing not at random. Missingness depends on the unobserved value itself. High earners refuse to state income. No imputation method fixes this without assumptions you cannot verify, so report sensitivity analyses.

Handling missing data: what each option costs you
MethodUse whenWhat it costs you
Listwise deletionMCAR, under 5% missingPower drops fast when many variables have gaps
Pairwise deletionCorrelation matrices onlyDifferent n for every cell; matrices can misbehave
Mean substitutionAlmost neverArtificially shrinks variance and biases correlations
Regression imputationA few numeric variables, MARUnderstates uncertainty; makes data look too clean
Multiple imputationMAR, any amountSome setup time; the defensible default
Full information maximum likelihoodSEM and regression contextsBuilt into the model; strong when available

Mean substitution quietly biases every variance and correlation downward. Multiple imputation is available in Stata (mi impute), R (the mice package) and SPSS (Multiple Imputation procedure).

Compare respondents with and without missing values on the variables you do have; systematic differences mean the data are not MCAR.

Step 8: Outliers: Investigate, Do Not Delete

An outlier is a data point that does not fit. That could mean an error, or it could mean the most interesting household in your sample.

Detection methodThresholdBest for
Z-scoreBeyond ±3Roughly normal variables
IQR ruleBeyond 1.5 × IQR from the quartilesSkewed variables, more robust
Boxplot inspectionVisualQuick screening across many variables
Mahalanobis distanceChi-square cutoffMultivariate outliers
Cook's distanceAbove 4/nInfluential cases in regression

The decision tree is short. Is it impossible (age 250)? Correct it from source if you can, or set it to missing. Is it possible but extreme (a household earning forty times the median)? Check for a unit or extra-zero error first: monthly income entered as annual, or 50,000 entered as 500,000. If it is genuine, keep it, and consider a transformation, a robust method, or reporting the analysis with and without it.

For income, land holding, expenditure and similar right-skewed variables that dominate Indian household survey work, a log transformation or median-based reporting usually works better than any deletion rule. Winsorising (capping values at, say, the 1st and 99th percentiles) is common in development economics, but it is a modelling choice, not a cleaning fix, and the uncapped variable should be kept. Deleting values because they are inconvenient is data manipulation, however well intentioned.

Screen by stratum or district: 40 acres is extreme in a smallholder district and ordinary elsewhere.

Step 9: Recoding, Other-Specify and Derived Variables

TaskWhy it matters
Reverse-score negative itemsOtherwise reliability collapses and scale means are meaningless
Code "other, please specify" textFrequent answers often belong in existing or new categories
Collapse rare categoriesChi-square needs expected counts of 5 or more in most cells
Create derived variablesPer-capita income, dependency ratio, asset index, food security score
Label everythingSo the output is readable a year later

"Other, please specify" responses are often underestimated. In a large survey, hundreds of open texts may say the same thing in different spellings and languages. Read them, build a coding frame, recode those that fit existing categories, and add new categories where a group is large enough to matter. Keep the original text.

Unreversed negatively worded items can push Cronbach's alpha towards zero, which is a useful diagnostic in itself. See reliability and validity in survey research and how to analyse Likert scale survey data for what comes next.

Derived variables should be built in the script, never typed in, and each should be checked against a few hand calculations. Per-capita measures need a clean household size, so derive them after the roster consistency checks in Step 5.

Step 10: Weights, Design Variables and Final Verification

If the sample was stratified or clustered, the clean file must carry the stratum, cluster (primary sampling unit) and sampling weight for every record. Without them, standard errors will usually be too small and proportions may be biased. Weights are calculated from the selection probabilities in the sampling design, sometimes adjusted for non-response; the design itself is covered in how to determine sample size for a household survey.

Before releasing the clean file, run a verification pass:

  1. Reconcile record counts: raw records, exclusions by reason, final records.
  2. Produce frequency tables for every categorical variable and summary statistics for every numeric one.
  3. Confirm no undeclared special codes remain (search for 97, 98, 99, 999, 9999 in the maximums).
  4. Re-run the skip logic and range checks on the clean file; they should all pass.
  5. Run the whole script from the raw file in a fresh session and confirm the output is identical.

Step 11: The Cleaning Log, and Why It Is Not Optional

Where analysis time actually goes

Cleaning routinely consumes a large share of the hours on a survey project, often more than the analysis itself. The output of that work should be three artefacts, not one:

  1. The raw file, never modified. Read-only, archived, exactly as it came from the field.
  2. The cleaning script or syntax, which turns the raw file into the clean one.
  3. The clean file, versioned and dated, which is the only one the analysis touches.

The cleaning log sits alongside the script and records each case-level decision in a form a reviewer can read without running code:

Record IDVariableOriginal valueNew valueRule or reasonSource of correctionDate
HH-0412land_owned4504.5Decimal point omitted; confirmed by field supervisorPhone call12 Mar
HH-1021whole recordkeptdroppedDuplicate ID; second interview of same householdBack-check13 Mar

Anyone should be able to delete the clean file and rebuild it by running the script. If they cannot, you do not have a reproducible analysis; you have a spreadsheet with an untraceable history. This is the same discipline that makes an SPSS thesis analysis survive a viva, and it matters more than which software you chose. The World Bank's DIME Wiki sets out the same approach for large field studies.

How to Clean Survey Data in Stata, R, SPSS and Excel

All four tools can do the job. What separates them is how easily the work can be scripted, repeated and audited.

TaskStataRSPSSExcel
Inspect variablesdescribe, codebook, inspectstr, summary, skimrDisplay Dictionary, FREQUENCIESFilters, pivot tables
Check unique IDsisid, duplicates reportcount by ID, janitor::get_dupesIdentify Duplicate CasesCOUNTIF, Remove Duplicates
Range and logic checksassert, list ifdplyr::filter, validate packageValidate Data, syntax IFConditional formatting, formulas
Declare missing codesmvdecode, extended missingna_if, labelled and havenMISSING VALUESManual find and replace
Recode and labelrecode, label definedplyr::case_when, factor labelsRECODE, VALUE LABELSLookup tables
Multiple imputationmi imputemiceMultiple ImputationNot practical
Audit traildo-file and log fileR script or Quarto reportSaved syntax and outputPower Query steps only

Stata is common in development and impact evaluation work, and do-files make the pipeline easy to audit. R is free, very flexible and well suited to reproducible reports; getting started with R for statistical analysis covers the basics. SPSS is widely used in Indian universities and is fine for cleaning as long as you paste and save syntax rather than clicking through menus; the trade-offs are compared in SPSS vs R for data analysis.

Excel is acceptable for small, simple datasets, for example a few hundred responses with no rosters. Its weakness is the audit trail: manual edits leave no record of what changed. If you must use Excel, keep the raw sheet untouched, do all changes in Power Query or in formula columns, and keep a written log. Watch for automatic date conversion and lost leading zeros on import.

Worked Example: An Illustrative 1,200-Household Baseline

The figures below are illustrative, not from a real project. They show how the checklist plays out on a typical CAPI baseline survey for a rural livelihoods programme.

Starting point. The server export holds 1,262 household submissions against a target of 1,200, plus member and plot rosters.

Steps 2 and 3, structure and duplicates. Village codes lost leading zeros on import and were re-read as text. The ID check finds 31 exact duplicate submissions (dropped) and 9 IDs used for two different households (re-assigned after the field team confirmed the correct IDs). Records: 1,231.

Step 4, respondent quality. Four records lack consent and are removed. The median interview took 52 minutes; 11 interviews took under 17 minutes. Back-checks confirmed all 11 as genuine small households, so they were kept. Twenty-seven training-day test forms were removed. Records: 1,200.

Steps 5 and 6, range, consistency and skip logic. Land operated did not equal land owned plus leased in for 64 households; 51 were unit errors (bigha entered as acres) fixed using the district conversion factor, and 13 were flagged as genuinely inconsistent and set to missing. Skip logic checks found 18 households with livestock sales but no livestock, all from an early form version with a routing error; they were set to "not applicable" after confirming the filter answer with audio recordings. Household size disagreed with the roster for 22 households, resolved by re-linking orphan rows.

Step 7, missing values. Income had 7% missing, concentrated among households with salaried members. That pattern suggests the data are not MCAR, so income was multiply imputed using household size, education, occupation, landholding and asset index, and the report included results with and without imputation.

Step 8, outliers. Three households reported monthly income above 15 times the median. Two were annual figures entered as monthly and were corrected after a phone check; one was a genuine trader household and was kept, with income analysed on a log scale.

Output. A clean file of 1,200 households with weights and design variables, a log of 214 case-level changes, and a single do-file that rebuilds everything from the raw export.

Cleaning Panel Data: Baseline, Midline and Endline

Impact evaluations add a second layer of cleaning, because the same households must be matched across rounds. The design is explained in how baseline and endline surveys power impact evaluation; for cleaning, the main tasks are:

  • ID matching. Check that every endline household maps to a baseline ID, and investigate mismatches using names, phone numbers and GPS rather than assuming a typing error.
  • Harmonising variables. Questions that changed wording, categories or recall period between rounds must be recoded to a common definition, or flagged as not comparable.
  • Attrition. Record which baseline households were not re-interviewed and why, then compare their baseline characteristics with those who stayed. Differential attrition between treatment and comparison groups can bias the estimate.

Clean each round with the same script structure, then build the panel in a separate script. That separation makes it far easier to run a difference-in-differences analysis with confidence that the change you measure is not a cleaning artefact.

How DSTechnoverse Helps

DSTechnoverse cleans and analyses survey data for researchers, CSR teams, NGOs, EIA consultants and businesses across India. Through our statistical and research data analysis service we take raw exports from ODK, KoboToolbox, SurveyCTO, CATI systems or paper data entry and deliver three things: the untouched raw file, a documented Stata, R or SPSS cleaning script, and a clean, labelled dataset with a cleaning log and codebook. Where we also run the fieldwork through our socio-economic and baseline survey service, cleaning rules are built into the questionnaire and daily checks from the start. Contact us to discuss your dataset.

Frequently Asked Questions

What are the main steps in survey data cleaning?

Protect the raw file, import and check structure, verify unique IDs and remove duplicates, apply respondent quality rules, run range, consistency and skip logic checks, declare and treat missing values, investigate outliers, recode and derive variables, attach weights and design variables, verify the final file, and record every change in a cleaning log. Do it all in a script so the clean file can be rebuilt.

How much missing data is acceptable?

There is no fixed threshold. Under 5% missing completely at random is generally unproblematic. Above about 10% you should consider multiple imputation rather than deletion, and report the pattern. The mechanism matters more than the percentage: 3% missing because high earners refused is worse than 15% missing because a tablet crashed.

Should I delete outliers from my survey data?

Only if they are impossible or demonstrably erroneous. First check for unit and extra-zero errors, then correct from source if you can. Extreme but plausible values usually carry real information. Consider a log transformation or a robust method instead, and if you do exclude cases, report the analysis both with and without them.

What are skip logic checks?

Skip logic checks confirm that conditional questions were answered by exactly the respondents who should have answered them. You test both directions: values present where the routing says the question should be skipped, and blanks where it should have been answered. Errors are common in paper surveys and in CAPI data collected across several form versions.

What is the difference between data cleaning and data screening?

Cleaning fixes errors such as wrong codes, impossible values, duplicates and routing mistakes. Screening checks whether the cleaned data meet the assumptions of your planned analysis, such as normality, homogeneity of variance and absence of multicollinearity. Cleaning comes first; screening decides which test you can run.

How long does survey data cleaning take?

It depends on survey length, rosters, collection mode and how much quality control happened in the field. As a rough guide, cleaning often takes 30 to 50% of total analysis hours. A 1,000-household CAPI survey with several rosters can take one to two weeks; paper surveys with manual entry usually take longer because they need double entry and reconciliation.

Can I clean survey data in Excel?

For small, simple datasets without rosters, yes. For anything larger it becomes risky, because manual Excel edits leave no record of what was changed, and Excel can silently convert codes to dates and drop leading zeros. Use Stata, R or SPSS syntax so every change is scripted and reproducible.

Which is better for survey data cleaning: Stata, R or SPSS?

All three work well if you script everything. Stata is the usual choice in development research and impact evaluation, R is free and strong for reproducible reports, and SPSS is common in universities. Choose the tool your analysts and reviewers know, and save the syntax. The audit trail matters more than the software.

Should I outsource survey data cleaning?

Outsourcing makes sense when the dataset is large, has rosters or several rounds, or when your team lacks scripting experience in Stata, R or SPSS. Insist on receiving the cleaning script and log, not just a clean file. How to hire a survey data analysis consultant lists the questions to ask before you commit.


Need help turning your data into defensible results? DSTechnoverse offers statistical and research data analysis services in SPSS, R, and Python — survey analysis, thesis and dissertation support, and business statistics. Get in touch to discuss your dataset.

Share

Tags

data cleaningsurveydata analysispreparationquality

Explore More Articles

Discover more insights and updates from DSTechnoverse

View All Articles