Cheatsheet module 4
Cheatsheet module 4: data cleaning and management
Principles
- Cleaning is not a fixed recipe. Raw data stays intact; save new variables separately and document every step.
- After every operation check: rows, NAs, Inf, duplicates. Words like “always” and “never” are almost always the trap.
Missing values (NA)
- Three routes: filtering (for this analysis only), imputation (risk of bias), deletion (safe if the share is small).
- R: sum(is.na(x)), colSums(is.na(df)), mean(x, na.rm = TRUE), complete.cases(df). Without na.rm, mean() returns NA.
- Error codes (-999) are NAs, not outliers: convert first, then analyse.
- Imputation with the mean: mean unchanged, standard deviation smaller.
Data inconsistencies
- Date formats, text variants, empty text, units, data types. Check str(df); as.numeric() on “18C” gives NA with only a warning.
- Duplicates: duplicated(). Also check impossible values (negative rainfall).
Outliers
- Investigate first: error, rare or real? Error: NA or correct. Skewed but real: log transformation. Do not remove automatically.
- Detection: 1.5 x IQR or z-score; document the criterion.
Merge and new variables
- rbind(): same columns, stack rows. merge(a, b, by = “key”): join columns; default keeps matches only (inner), all.x = TRUE keeps left, all = TRUE both.
- Duplicates in the key multiply rows. Count rows before and after.
- New variables: mutate, cut() for binning, ifelse(). After log(0) you get -Inf: check.
- group_by + summarise: also report n. Long = row per observation, wide = column per measurement.
Scaling
- Normalization: (x - min) / (max - min), range 0 to 1, sensitive to outliers.
- Standardization: z = (x - mean) / sd, unbounded. Does not make data normal.
- Needed for K-Means, kNN, PCA, SVM.
Reading R output
- Smartphones (1224 rows): lowest_price and highest_price 260 NA (21.2%), memory_size 112 (9.2%); mean(lowest_price, na.rm = TRUE) = 7716.019 over 964 values.
- best_price: mean 7941.207 (all rows) against 8567.024 after complete.cases on the three price columns (964 rows): dropping rows shifts the mean.
- Imputation PreferTrain: mean 42.511 stays, sd 27.698 to 27.132.
- Weather data: -999 in TEMP, 72 of 2976 July hours (2.42%). July mean -2.43 raw, 22.28 after NA.
- merge(Wr, maand, by = “REF”): 37236 rows stay 37236 (nrow equal, so no duplicates in the key).
- Per group: EMUI n = 2; WindowsPhone has 0 lowest_price values (NaN). Report n.