Data cleaning and management - explained simply
Real data is messy. Data scientists spend an estimated 60% of their time cleaning and organizing data. Poorly prepared data leads to poor decisions: in an example from the slides, CSV files from laboratories were not loaded properly, so test results were not followed up. Module 4 teaches you the steps to get data ready for analysis. It is a workshop week: there is no video, you work in RStudio with the Chicago Divvy Bikes and weather data. At the exam you do not write R code, but you read code and output and judge the choices.
Data cleaning is detecting and correcting errors and inconsistencies in a dataset so that the data is accurate, consistent, complete and reliable for models, reports and decisions. There is no fixed recipe: every dataset needs its own actions, and practice helps.
In R a missing value is NA. Causes: data loss during collection or transfer, entry errors, or questions that did not apply (skip patterns). Consequence: biased results, less power or error messages.
Three ways to deal with them:
- Filtering: leave out NAs only for the analysis you are doing now. The original data stays intact.
- Imputing: replace NAs with the mean, the median or another estimate. Risk: bias if done carelessly. With mean imputation the mean stays the same, but the standard deviation becomes smaller.
- Deleting: dropping rows with NAs is safe if only a small part is affected. If it is a lot (think of a quarter of the rows), it can distort the outcome.
Note that functions like mean() return NA unless you use na.rm = TRUE.
The same information is recorded in different ways: date formats (MM/DD/YYYY versus DD-MM-YYYY), text variants (“Male”, “male”, “M”), data types (text versus factor), units (euros and dollars, kilos and pounds). Solution: standardize formats, convert units, always check for duplicates, and fix typos. In R you convert text with a limited number of categories with as.factor() and dates with a function from the lubridate package.
An outlier is a value that deviates strongly from the rest. It can be an error (age 328), a rare but valid value or real variation. Approach: first investigate (error or valid?), remove a clear error (or set it to NA), or transform with log or another function. The lesson of the slides: do not remove outliers blindly, understand them first; sometimes they tell the most interesting story.
Data is often spread over several files. What you do depends on the shape:
- same variables, one file per month: stack rows with
rbind(); - same customers, different variables: join columns with
merge(..., by = "customer_id"); - many transactions and few customers (many-to-one):
merge(..., all.x = TRUE)keeps all transactions.
Note: choose a key (), remove duplicates before merging, make sure data types match, decide what to do with rows without a match and always check the output after merging.
Kinds: transformations (log(income)), (age into child, adult, senior), indicators (is_high_income = income > 100000), combinations (revenue = price * quantity), date parts (year from a date) and rankings. Rules: document new variables, check for NA and Inf after a transformation (think of log(0)), never overwrite the raw columns and choose clear names.
Some models (K-Means, kNN, PCA, SVM) are sensitive to scale; variables with a larger range would otherwise dominate. Normalization scales to 0 to 1: (x - min) / (max - min). Standardization gives z = (x - mean) / standard deviation; the result has no fixed bounds.
The assignment investigates the relationship between weather and bike use in Chicago: load and explore the data, check types, handle missing values and , create new variables (duration, distance), clean the weather data, both datasets on the hour (the key is an hourly timestamp) and finally do exploratory analyses with tests and correlations.
There are 2 multiple-choice questions on module 4, mostly about reading code and output: what does this line do, what does this NA count mean, which choice is sensible? You do not write code. Remember: keep the raw data, document what you do, and check after every operation whether the result is right.
Data cleaning and management - exam material
is detecting and correcting errors and inconsistencies to raise data quality (accurate, consistent, complete, reliable) for modelling, reporting and decisions. It is not a standard process: the actions depend on the data. It takes much time (an estimated 60% of data scientists’ work) and poor preparation leads to poor decisions. Module 4 is a workshop week; the exam tests reading R code and output (about 2 multiple-choice questions), not writing it.
A missing value is a data point that was not recorded or is not available (in R: NA). Causes: loss during collection or transfer, entry errors or omissions, not-applicable answers (skip patterns). Consequences: bias, less power, errors in the analysis.
| Approach | What | Advantage or risk |
|---|---|---|
| Filtering | leave out NAs only for this analysis | original dataset stays intact, flexible if you revise |
| Imputing | replace by mean, median or another estimate | risk of bias; mean imputation reduces the spread |
| Deleting | drop rows with NAs | safe for a small part; distortion if much data is missing |
Useful R operations to recognise: is.na(x), sum(is.na(x)) (number of NAs), colSums(is.na(df)) (per column), mean(x, na.rm = TRUE), complete.cases(df) and na.omit(df). Note the difference between a percentage per column and the number of complete cases: a dataset with 10% NA in three columns can lose far more than 10% of the rows with na.omit(). With mean imputation the mean does not change, but the standard deviation falls (larger n, same sum of squares), and associations become weaker.
Examples: date formats (MM/DD/YYYY versus DD-MM-YYYY), categorical variants (“Male”, “male”, “M”), data types (character versus factor), units (euros and dollars, kilos and pounds). Approach: standardize formats (date/time, text case, types), convert units, always check for duplicates (duplicated(), unique()), fix typos and wrong entries with the same structure.
Types and factors: str(df) shows the types; as.factor(), as.numeric() and as.Date() (or lubridate functions such as ymd()) convert. A factor has levels; a variable with numbers stored as text must first become numeric before you can take a mean. Recoding can be done with ifelse(), cut() () or dplyr case_when().
An outlier is a data point that differs strongly from the rest; it can point to an error, a rare event or real variation, and can distort the analysis. Example from the slides: ages 21, 25, 35, 30, 32, 68 (striking but plausible) versus 328 (impossible).
Approach: investigate (error or rare but valid?), remove if it is clearly a mistake, transform (log or another function) for a skewed distribution. Do not remove blindly: understand why first. A common detection rule is the boxplot rule (beyond 1.5 times the IQR from the quartile) or a z-score; you must be able to justify and document the chosen criterion. An error code such as -999 for “unknown” is not an outlier but an NA that you must convert.
| Situation | Function |
|---|---|
| same variables, several files (months): stack rows | rbind() |
| same units, different variables: join columns on a key | merge(a, b, by = "customer_id") |
| many-to-one, keep all transactions | merge(a, b, all.x = TRUE) |
Note: choose a , remove duplicates beforehand, make data types match (no mix of integer and character), decide what to do with non-matches (a customer without transactions, a transaction from a customer not in the list) and check the output after merging (number of rows!). With all.x = TRUE unmatched rows from the left table stay with NA in the new columns; with default merge() they disappear (inner join). A common mistake is joining on a key with duplicates: the number of rows then increases.
Kinds: transformation (log(income), sqrt(price)), (age into child, adult, senior), indicator or flag (is_high_income = income > 100000), combination (revenue = price * quantity), date parts (lubridate::year(order_date)) and ranking or score. Rules: document new variables, check for NA and Inf after a transformation (such as log(0)), do not change the raw columns directly, use clear names.
With dplyr you use mutate() for new columns, filter() for rows, select() for columns, group_by() with summarise() for summaries and the pipe %>% or |> to chain steps. Data can be long (one row per observation, for example per hour or per measurement) or wide (one column per measurement); models and plots usually expect long, summary tables are often wide.
Reason: models that are sensitive to scale (K-Means, kNN, PCA, SVM) let variables with a large range dominate; scaling makes the comparison fair.
| Method | Formula | Output range |
|---|---|---|
| Normalization | x’ = (x - min) / (max - min) | [0, 1] |
| Standardization | z = (x - mu) / sigma | unbounded |
Normalization is sensitive to (min and max determine everything); standardization does not change the shape of the distribution.
Tasks: load and explore the dataset (str, summary), check variable types (factor, time object), remove the rows with docked_bike, handle NAs, deal with in trip duration and distance, create new variables (duration in minutes or hours, distance with the Haversine formula), clean and extend the weather data (daily averages for temperature and wind speed, daily total for precipitation), both datasets on an hourly timestamp that you create in both, and exploratory (model-free) analyses with tests and correlations.
- Deleting rows with NA without looking at how many there are or why they are missing.
- Leaving error codes (-999, 9999) in as real values.
- Merging without checking the row count; duplicates in the key.
- Overwriting raw columns instead of creating a new variable.
- Seeing mean imputation as neutral: it reduces the spread.
- Removing automatically.
About 2 multiple-choice questions on module 4. No code writing; reading instead: what does sum(is.na(x)) count, what effect does all.x = TRUE have, which approach fits this outlier, what is the risk of this imputation? The formula sheet is hardly relevant here; the reasoning counts.
Module 4 according to the lecturer
Introduction and exam tips
Module 4 according to the lecturer
Module 4 is a workshop week without video: Harwin de Vries delivers the material through slides (BM21MIM-P - Module 4) and a workshop in RStudio. The lecturer layer therefore consists of verbatim slide quotes (English), with an explanation in my own words. There are no lecture transcripts for this module.
Dia 4 uit BM21MIM-P - Module 4:
60%: the estimated fraction of time that data scientists spend cleaning and organizing data
Most of a data scientist’s work is preparation, not modelling. So expect cleaning to take a lot of time in the group assignment too.
Dia 8 uit BM21MIM-P - Module 4:
The process of detecting and correcting errors or inconsistencies in a dataset to improve its quality and make it ready for analysis.
This is the definition you can recognise at the exam. The goal (slide 8): data that is accurate, consistent, complete and reliable for models, reporting and decisions.
Dia 9 uit BM21MIM-P - Module 4:
Missing data can lead to biased results, reduce statistical power, or cause errors in analysis.
Three consequences: bias, less power and errors. That is why you always first count how many NAs there are and where they are.
Dia 10 uit BM21MIM-P - Module 4:
Filter out missing values only for the specific analysis.
The advantage is on the same slide: the original dataset stays intact, which gives flexibility if you adjust your analysis later. Imputing can give bias if done carelessly, and deleting is safe only for a small part.
Dia 14 uit BM21MIM-P - Module 4:
Is it an error or a rare but valid case?
This is the first question for every outlier. If it is clearly a mistake (age 328) you remove it; for a skewed distribution you can transform with a log. The message of the slide: do not just remove outliers, understand them.
Dia 17 uit BM21MIM-P - Module 4:
Always double-check output after merging
errors are silent: a wrong type or key gives no error message but a wrong number of rows. Check rows, NAs and duplicates. Slide 17 also says: choose a , remove duplicates before merging and make data types match.
Dia 19 uit BM21MIM-P - Module 4:
Always document new variables
Also (slide 19): check for NA or Inf after a transformation such as log(0), do not change raw columns directly and use clear names. This fits the group assignment, where you must be able to justify your choices.
The slides stress reasoned choices and checking: keep raw data intact, document, check after every operation. Multiple-choice questions on module 4 (about 2) ask for reading code and output and choosing the most sensible approach, not for writing R code.
A web shop analyses 1224 smartphones in phones_data.csv (13 columns). Real output from m4-ontbrekend-tellen and m4-ontbrekend-effect-gemiddelde.
- Missing: lowest_price and highest_price each miss 260 values (21.2%), memory_size 112 (9.2%), battery_size 10 (0.8%) and screen_size 2 (0.2%).
- Only 852 of the 1224 rows are complete. If you delete every row with a missing value, you lose almost a third of the data.
mean(Ph$lowest_price)gives NA. Withna.rm = TRUEthe mean is 7716.019, computed over 964 observations, not 1224.- If you filter with complete.cases on the three price columns, 964 rows remain and the mean of best_price rises from 7941.207 to 8567.024. The choice therefore changes the result.
- So choose deliberately, keep the raw data intact and document the choice.
- After every operation, check with
dim(),nrow()orcolSums(is.na(...))how many rows are left and whether the columns are still right, so you notice any unnoticed loss of observations immediately. - In your answer, always report the number of observations on which a mean or model is based.
Case: the smartphone dataset above, based on assignment 1 of module 4.
- Size (2 p): lowest_price misses 260 of 1224 values (21.2%); only 852 rows are complete, so deleting all incomplete rows costs almost a third of the data.
- Consequence (2 p): the mean of best_price differs between all rows (7941.207) and the complete rows (8567.024). Dropping rows therefore changes the outcome and can give a distorted picture.
- Approach (3 p): first investigate why values are missing, filter only on the columns you need, keep the raw data and document every choice.