Mathew K Analytics

Lesson 7 · R Programming: Zero to Expert

Data Cleaning in R: Fix Messy Real-World Data with the Tidyverse (Full Course) | R 107

Video 7 of R Programming: Zero to Expert. Import, inspect, fix and validate data that fights back. R script: 07datacleaning.R. Download it from this page…

⬇ Download R script⬇ R notebook (.ipynb)

What you'll learn

Files for this lesson

Save these in one folder, open the script in RStudio and set that folder as the working directory (Session → Set Working Directory → To Source File Location).

📓 Full notebook

Download .ipynb

Cleaning Messy Real-World Data in R#

Video 7 of R Programming: Zero to Expert.

Import, inspect, fix and validate data that fights back.

R script: 07_data_cleaning.R. Download it from this page and open it in RStudio, or run this notebook with an R kernel (for example in Google Colab: Runtime → Change runtime type → R).

Setup#

library(tidyverse)
library(readxl)
library(jsonlite)

The tidyverse prints the eight core packages it attached, and a note that dplyr filter and lag now hide two base R functions with the same names. That is normal. jsonlite tells us it masks flatten from purrr. We will not use flatten today, so we can ignore it.

A messy file, just like the real thing#

We write a small CSV export with every classic problem in it.

raw_lines <- c(
  "Order ID,Customer Name , Order Date,Amount,Region,Status",
  "1001,  alice SMITH,2024-01-05,\"$1,200.50\",north,Shipped",
  "1002,Bob Jones,05/01/2024,350,North ,shipped",
  "1003,Carla Diaz,Jan 7 2024,N/A,south,Pending",
  "1004,bob jones,2024-01-08,\"$75.00\",NORTH,Cancelled",
  "1005,Dev Patel,2024-01-09,-,East,shipped",
  "1002,Bob Jones,05/01/2024,350,North ,shipped",
  "1006,Eve Ng,2024-01-10,9999999,West,Shipped"
)
writeLines(raw_lines, "orders_raw.csv")

Step 1: read it and look before you touch it#

orders0 <- read_csv("orders_raw.csv")
orders0

First, readr reports what it found: seven rows and six columns. It guessed that Order ID is a number, a double, and that the other five columns are character text. Then the tibble itself. Notice the backticks around the column names, because they contain spaces. Amount is text, the dates are text, and order one thousand and two appears twice.

spec(orders0)

spec confirms the guesses. Only Order ID was read as a number. Amount and Order Date are plain character columns, so right now R cannot add up money or sort by date.

names(orders0)

Here we can see the raw names, spaces and capitals included.

glimpse(orders0)

glimpse shows seven rows and six columns, then one line per column. The values running across make the mess obvious: mixed capitals, three date styles, dollar signs, an N slash A and a dash.

problems(orders0)

An empty table, zero rows. readr had no problems, because every column it could not read as a number it simply kept as text. No errors does not mean clean data.

Step 2: tell readr what missing looks like#

na_codes <- c("", "NA", "N/A", "-")
orders1 <- read_csv("orders_raw.csv", na = na_codes)
orders1$Amount

Now the N slash A and the dash have become real missing values, shown as N A without quotes. The other amounts are still text, with their dollar signs.

Declaring column types up front#

read_csv("orders_raw.csv", na = na_codes,
         col_types = cols(
           `Order ID` = col_integer(),
           Amount = col_double(),
           .default = col_character()
         )) |>
  problems()

Two problems. In row two and row five, column four, readr expected a double but found text with a dollar sign. Declaring types turns silent surprises into a clear list of failures you can fix.

Step 3: clean column names#

clean_names <- function(df) {
  nm <- names(df)
  nm <- str_trim(nm)
  nm <- str_to_lower(nm)
  nm <- str_replace_all(nm, "[^a-z0-9]+", "_")
  nm <- str_remove_all(nm, "^_|_$")
  names(df) <- nm
  df
}
orders2 <- clean_names(orders1)
names(orders2)

Every name is now lower case, with underscores instead of spaces, and the stray space after customer name has gone.

Step 4: remove duplicate rows#

orders2 |>
  add_count(across(everything()), name = "copies") |>
  filter(copies > 1)

Two rows come back, both for order one thousand and two, and the copies column says each row appears twice. That is our duplicate.

orders3 <- distinct(orders2)
nrow(orders2)
nrow(orders3)

Seven rows before, six after. Exactly one duplicate row was removed.

orders3 |> count(order_id) |> filter(n > 1)

Zero rows, so no order I D appears more than once.

Step 5: fix text columns#

orders3 |> distinct(customer_name)

Six distinct names, but only five real people. Bob Jones appears once with capitals and once in lower case, so R treats them as two different customers.

orders4 <- orders3 |>
  mutate(
    customer_name = str_squish(customer_name),
    customer_name = str_to_title(customer_name),
    region = str_to_title(str_squish(region)),
    status = str_to_lower(str_squish(status))
  )
orders4 |> count(customer_name)
orders4 |> count(region)
orders4 |> count(status)

Now there are five customers, and Bob Jones has two orders, which is correct. Regions collapse from five spellings into four clean values, with North holding three orders. And statuses become three clean values: one cancelled, one pending and four shipped.

Step 6: turn text into numbers#

class(orders4$amount)
as.numeric(orders4$amount)

class says character. as numeric only manages the plain numbers, three hundred and fifty and the huge one. Anything with a dollar sign or a comma becomes N A, and R warns that N As were introduced by coercion. That warning is R telling you that you just lost data.

parse_number(orders4$amount)

parse number keeps every amount: one thousand two hundred point five, three fifty, seventy five and the huge value. The two N As are the genuinely missing ones.

parse_number("1.200,50", locale = locale(decimal_mark = ","))

The European style one point two hundred comma fifty is read correctly as one thousand two hundred point five.

orders5 <- orders4 |>
  mutate(amount = parse_number(amount))
summary(orders5$amount)

The summary shows a minimum of seventy five and a median of about seven hundred and seventy five, but the mean is about two point five million. When the mean is thousands of times bigger than the median, one extreme value is pulling it.

pct <- c("12%", "7.5 %", "100%", "n/a")
parse_number(pct, na = "n/a") / 100

Twelve percent becomes zero point one two, seven and a half percent becomes zero point zero seven five, one hundred percent becomes one, and n slash a is missing.

weights <- c("1.2 kg", "850 g", "2kg", "500 g")
tibble(raw = weights,
       value = parse_number(raw),
       unit = str_extract(raw, "[a-z]+$"),
       kg = if_else(unit == "g", value / 1000, value))

Every weight is now in kilograms: one point two, zero point eight five, two, and zero point five. The unit column shows exactly which values were converted.

Step 7: dates in several formats#

orders5$order_date

Year first with dashes, day first with slashes, and a month name in words, all in one column.

ymd(orders5$order_date)

ymd parses the four year first dates, but the other two fail and become N A, with a warning that two failed to parse.

fmts <- c("Ymd", "dmY", "bdY")
parse_date_time(orders5$order_date, orders = fmts)

This time all six dates parse. Both the slash date and Jan seven became proper dates. The U T C at the end is a time zone, because parse date time returns a date and time.

orders6 <- orders5 |>
  mutate(order_date = as_date(
    parse_date_time(order_date, orders = fmts)
  ))
orders6 |> select(order_id, order_date) |>
  mutate(day = wday(order_date, label = TRUE))

Every order now has a real date, and R can tell us the day of the week, from Friday the fifth of January to Wednesday the tenth.

Date times and time zones#

stamps <- c("2024-01-05 23:30:00", "2024-01-06 02:15:00")
utc <- ymd_hms(stamps, tz = "UTC")
local <- with_tz(utc, "Australia/Adelaide")
tibble(utc, local, local_day = as_date(local))

Eleven thirty at night U T C on the fifth of January is ten in the morning on the sixth in Adelaide, because Adelaide is ten and a half hours ahead in summer. Both sales fall on the sixth locally.

Two date traps from Excel#

excel_days <- c(45292, 45323, 45351)
as_date(excel_days, origin = "1899-12-30")

The three numbers become the first of January, the first of February, and the twenty ninth of February twenty twenty four, a leap day.

mixed <- c("2024-02-30", "2024-13-01", "2024-12-31")
ymd(mixed, quiet = TRUE)
sum(is.na(ymd(mixed, quiet = TRUE)))

The two impossible dates become N A, and only the thirty first of December survives. The count says two dates failed. In a real script, if that number is not zero, go and look at those rows.

Step 8: suspicious values#

q <- quantile(orders6$amount, c(0.25, 0.75), na.rm = TRUE)
iqr <- q[2] - q[1]
q[2] + 3 * iqr

The cut off comes out at about ten million, which is higher than the suspicious order itself. With so few values, the huge amount inflates the upper quartile, so the quartile rule cannot catch it. Outliers can hide themselves.

m <- median(orders6$amount, na.rm = TRUE)
s <- mad(orders6$amount, na.rm = TRUE)
upper <- m + 5 * s
upper
orders6 |> filter(amount > upper)

The median based cut off is about four thousand nine hundred and forty seven dollars. And exactly one order sits above it: order one thousand and six, from Eve Ng, at nearly ten million. Now we have caught it.

orders7 <- orders6 |>
  mutate(
    amount_flag = if_else(amount > upper, "check", "ok",
                          missing = "missing"),
    amount = if_else(amount > upper, NA_real_, amount)
  )
orders7 |> select(order_id, amount, amount_flag)

Order one thousand and six is flagged check and its amount is now missing. The two orders that never had an amount are labelled missing, and the rest are ok.

Step 9: missing values#

colSums(is.na(orders7))

Three amounts are missing, the two original gaps plus the one we removed. Every other column is complete, including the flag.

orders7 |> filter(if_any(everything(), is.na))

Here are those three rows. The flag column explains why each amount is missing, which is exactly why we kept it.

orders7 |>
  drop_na(amount) |>
  nrow()

Dropping them leaves only three orders, half of our data. That is the danger of dropping rows.

orders7 |>
  mutate(amount = replace_na(amount, 0)) |>
  pull(amount)

The three missing amounts are now zeros.

med <- median(orders7$amount, na.rm = TRUE)
coalesce(orders7$amount, med)

The median of the known amounts is three hundred and fifty, so each missing amount becomes three hundred and fifty.

Step 10: recode categories#

orders8 <- orders7 |>
  mutate(
    status_group = case_when(
      status %in% c("shipped") ~ "complete",
      status %in% c("pending") ~ "open",
      status %in% c("cancelled") ~ "lost",
      .default = "unknown"
    ),
    region = factor(region, levels = c("North", "South", "East", "West"))
  )
orders8 |> count(status_group, region)

North has two complete orders and one lost. East and West have one complete order each, and South has the single open order. The regions appear in the order we chose, not alphabetically.

Step 11: validate with rules#

stopifnot(
  !anyDuplicated(orders8$order_id),
  all(orders8$amount >= 0, na.rm = TRUE),
  all(!is.na(orders8$order_date)),
  all(orders8$status_group != "unknown")
)
"All checks passed"

All four rules hold, so we see All checks passed.

check_rule <- function(ok, msg) {
  if (!ok) stop("Check failed: ", msg, call. = FALSE)
  invisible(TRUE)
}
check_rule(max(orders8$amount, na.rm = TRUE) < 5000, "huge amount")
try(check_rule(nrow(orders8) > 10, "too few rows"))

The second check fails with our own clear message, Check failed: too few rows. The first check printed nothing, which is exactly what passing should look like.

Typos in categories: fuzzy matching#

countries <- c("Australia", "Austrlia", "australia ",
               "New Zealand", "New Zeland", "NZ", "Fiji")
valid <- c("Australia", "New Zealand", "Fiji")
adist(str_squish(countries), valid, ignore.case = TRUE)

Read the first row: Australia is zero edits from Australia, nine from New Zealand and eight from Fiji. Austrlia, with the missing a, is one edit away from Australia.

d <- adist(str_squish(countries), valid, ignore.case = TRUE)
best <- valid[apply(d, 1, which.min)]
tibble(typed = countries, best, distance = apply(d, 1, min))

The typos are fixed: Austrlia and New Zeland are one edit from the right answer. But look at NZ. It is matched to Fiji, because two letters are closer to Fiji than to New Zealand. Fuzzy matching is a helper, never a final answer.

lookup <- tribble(~typed, ~country,
                  "NZ", "New Zealand",
                  "Aus", "Australia")
tibble(typed = countries) |>
  left_join(lookup, by = "typed") |>
  mutate(country = coalesce(country, best))

Now NZ correctly becomes New Zealand from the lookup table, and every other value keeps its fuzzy match. All seven rows have a proper country.

Blank cells in grouped reports#

report <- tibble(
  manager = c("Ana", NA, NA, "Ben", NA),
  rep = c("Joe", "Kim", "Lee", "Max", "Ned"),
  sales = c(10, 12, 9, 15, 11)
)
report |> fill(manager, .direction = "down")

Ana now appears for Joe, Kim and Lee, and Ben for Max and Ned.

report |>
  fill(manager) |>
  group_by(manager) |>
  summarise(reps = n(), sales = sum(sales))

Ana manages three reps with total sales of thirty one, and Ben two reps with twenty six.

Padding IDs and fixing codes#

codes <- c(42, 7, 1234, 815)
str_pad(codes, width = 4, pad = "0")
sprintf("SKU-%04d", codes)

Forty two becomes zero zero four two, seven becomes zero zero zero seven, and the longer codes are unchanged. And sprintf gives S K U dash zero zero four two, and so on.

Rare categories#

set.seed(7)
channel <- sample(c("Web", "Store", "Phone", "Fax", "Telex"), 200,
                  replace = TRUE, prob = c(.6, .3, .07, .02, .01))
fct_count(channel, sort = TRUE)
fct_lump_n(channel, n = 3) |> fct_count(sort = TRUE)

Web has one hundred and twelve orders and Store sixty eight. Phone has twelve, Fax six and Telex only two. After lumping, Fax and Telex are combined into Other, with eight orders.

Checking codes against a reference table#

regions_ref <- tibble(
  region = c("North", "South", "East", "West"),
  manager = c("Ana", "Ben", "Cy", "Di")
)
new_orders <- tibble(order_id = 2001:2004,
                     region = c("North", "Sth", "West", "Central"))
new_orders |> anti_join(regions_ref, by = "region")

Two orders come back: order two thousand and two with the region S T H, and order two thousand and four with Central. Neither is on the official list.

new_orders |> semi_join(regions_ref, by = "region")
new_orders |> left_join(regions_ref, by = "region")

semi join keeps the two orders with valid regions, North and West. The left join keeps all four orders. North gets Ana and West gets Di, while S T H and Central get N A for manager.

Tidy data: reshaping wide tables#

Each variable a column, each observation a row.

sales_wide <- tribble(
  ~store, ~q1_2023, ~q2_2023, ~q1_2024, ~q2_2024,
  "Adelaide", 120, 135, 150, 160,
  "Perth",     90,  NA, 110, 125
)
sales_wide

A wide table: one row per store and one column per quarter. Perth has a missing value for the second quarter of twenty twenty three.

sales_long <- sales_wide |>
  pivot_longer(
    cols = -store,
    names_to = c("quarter", "year"),
    names_sep = "_",
    values_to = "sales",
    values_drop_na = TRUE
  ) |>
  mutate(year = as.integer(year))
sales_long

Now there are seven rows, one per store and quarter, with separate quarter and year columns. Perth's missing quarter has been dropped.

sales_long |>
  group_by(store, year) |>
  summarise(total = sum(sales), .groups = "drop")

Adelaide sold two hundred and fifty five in twenty twenty three and three hundred and ten in twenty twenty four. Perth only has one quarter for twenty twenty three, ninety, so be careful comparing its years.

sales_long |>
  pivot_wider(names_from = year, values_from = sales)

Years are columns again, with one row per store and quarter. The missing Perth quarter comes back as N A.

Splitting and combining columns#

people <- tibble(
  full_name = c("Smith, Alice", "Jones, Bob", "Diaz, Carla"),
  phone = c("08 8123 4567", "(08) 9555-1234", "0412 345 678")
)
people |>
  separate_wider_delim(full_name, delim = ", ",
                       names = c("last", "first"))

Smith, Alice became a last name of Smith and a first name of Alice, and the same for the others.

people |>
  mutate(digits = str_remove_all(phone, "[^0-9]"),
         n = str_length(digits))

All three phone numbers are now plain strings of digits, and each has exactly ten digits, so they all pass our length check.

Regular expressions: find patterns in text#

notes <- c("Call 0412 345 678 today",
           "Email bob@shop.com re invoice INV-2041",
           "No contact details",
           "Invoices INV-2042 and INV-2043 overdue")
str_detect(notes, "INV-")
str_extract(notes, "INV-\\d{4}")
str_extract_all(notes, "INV-\\d{4}")
str_extract(notes, "[\\w.]+@[\\w.]+")

str detect returns true for the second and fourth notes, the ones with invoices. str extract finds I N V two zero four one in the second note, but only the first invoice in the fourth note. str extract all returns every match, including both invoices from the last note. Notes with no match get an empty character vector. And the email pattern finds bob at shop dot com, with N A everywhere else.

Reading many files at once#

dir.create("monthly", showWarnings = FALSE)
for (m in c("jan", "feb", "mar")) {
  tibble(store = c("Adelaide", "Perth"),
         sales = round(runif(2, 100, 200))) |>
    write_csv(file.path("monthly", paste0(m, ".csv")))
}
files <- list.files("monthly", full.names = TRUE)
files

The three files are listed alphabetically, so February comes before January. Sort them yourself if order matters.

all_months <- read_csv(files, id = "file",
                       show_col_types = FALSE) |>
  mutate(month = str_remove(basename(file), ".csv$"))
all_months

Six rows in one table, two stores for each of three months, and the file and month columns record where every row came from. Your random sales numbers match mine because we set the seed earlier.

Reading Excel files#

library(writexl)
write_xlsx(
  list(orders = orders8, sales = sales_long),
  "shop_data.xlsx"
)
excel_sheets("shop_data.xlsx")

The workbook has two sheets, orders and sales, exactly as we named them in the list.

sales_x <- read_excel("shop_data.xlsx", sheet = "sales")
sales_x

The sales sheet comes back with all seven rows. Notice that year is now a double, because Excel stores every number the same way.

read_excel("shop_data.xlsx", sheet = "orders",
           range = "A1:D4")

Only four columns, from A to D, and three data rows, because row one holds the headers. The order date arrives as a date time, since Excel has no plain date type.

all_sheets <- excel_sheets("shop_data.xlsx") |>
  set_names() |>
  map(\(s) read_excel("shop_data.xlsx", sheet = s))
map_int(all_sheets, nrow)

The orders sheet has six rows and the sales sheet seven.

JSON: data from the web#

json_txt <- '[
  {"id": 1, "name": "Alice", "orders": [120, 80]},
  {"id": 2, "name": "Bob", "orders": [45]},
  {"id": 3, "name": "Carla", "orders": []}
]'
customers <- fromJSON(json_txt)
customers

A data frame with three customers. The orders column shows one hundred and twenty and eighty for Alice, forty five for Bob, and nothing for Carla.

str(customers)

id is an integer and name is character, but orders is a list of three: two values for Alice, one for Bob, and an empty vector for Carla.

customers |>
  unnest_longer(orders, keep_empty = TRUE)

Four rows: two for Alice, one for Bob, and one for Carla with an N A order, so she was not lost.

customers |>
  mutate(n_orders = lengths(orders),
         total = map_dbl(orders, sum))

Alice placed two orders worth two hundred, Bob one worth forty five, and Carla none, so her total is zero.

toJSON(sales_long, pretty = TRUE)

Each row became a JSON object in curly braces, with the column names as keys.

A reusable data quality report#

dq_report <- function(df) {
  tibble(
    column = names(df),
    type = map_chr(df, \(x) class(x)[1]),
    missing = map_int(df, \(x) sum(is.na(x))),
    unique = map_int(df, n_distinct),
    example = map_chr(df, \(x) as.character(x[1]))
  )
}
dq_report(orders0)

For the raw file: six columns, mostly character, no missing values and six unique values in almost every column. On paper it looks clean, which is exactly why you must look deeper.

dq_report(orders8)

For the clean table, the types are right: a Date, a numeric amount and a factor region. Customer names drop to five unique values, statuses to three, and the report honestly shows three missing amounts.

Project: clean a customer survey export#

One pipeline, from raw file to analysis-ready table.

survey_raw <- c(
  "Resp ID,Submitted,Age,Country,Satisfaction (1-5),Spend ($)",
  "r1,2024-03-01 09:15,34,australia,5,\"$1,050\"",
  "r2,01/03/2024 10:02,29,Australia ,4,300",
  "r3,2024-03-02 11:30,-1,New Zealand,6,120",
  "r4,2024-03-02 14:45,41,NZ,3,",
  "r5,03/03/2024 08:20,52,australia,2,\"$2,400\"",
  "r2,01/03/2024 10:02,29,Australia ,4,300"
)
writeLines(survey_raw, "survey_raw.csv")
survey <- read_csv("survey_raw.csv", na = na_codes,
                   col_types = cols(.default = "c")) |>
  clean_names() |>
  distinct() |>
  mutate(
    submitted = parse_date_time(submitted, c("Ymd HM", "dmY HM")),
    age = parse_number(age),
    age = if_else(between(age, 16, 100), age, NA_real_),
    country = str_to_title(str_squish(country)),
    country = recode(country, "Nz" = "New Zealand"),
    satisfaction = parse_number(satisfaction_1_5),
    satisfaction = if_else(satisfaction %in% 1:5,
                           satisfaction, NA_real_),
    spend = parse_number(spend)
  ) |>
  select(resp_id, submitted, age, country, satisfaction, spend)
survey

Five respondents remain, because the duplicate submission was removed. Every timestamp is a real date time. Respondent three has a missing age and a missing satisfaction, because minus one and six were impossible. Respondent four has a missing spend, and both New Zealand spellings now match.

stopifnot(!anyDuplicated(survey$resp_id),
          all(survey$satisfaction %in% c(1:5, NA)))
colSums(is.na(survey))

The checks pass silently. Then the missing counts: one age, one satisfaction and one spend.

survey |>
  group_by(country) |>
  summarise(
    respondents = n(),
    avg_satisfaction = mean(satisfaction, na.rm = TRUE),
    total_spend = sum(spend, na.rm = TRUE)
  )

Three Australian respondents with an average satisfaction of about three point six seven and total spend of three thousand seven hundred and fifty. Two from New Zealand averaging three, with one hundred and twenty spent.

write_csv(survey, "survey_clean.csv")
write_rds(survey, "survey_clean.rds")
file.exists(c("survey_clean.csv", "survey_clean.rds"))

Both say true, so both files were written.

Strange characters and encodings#

accented <- c("Jos\u00e9", "Zo\u00eb", "M\u00fcller")
names_latin1 <- iconv(accented, "UTF-8", "latin1")
writeLines(names_latin1, "old_system.csv", useBytes = TRUE)
read_lines("old_system.csv")
read_lines("old_system.csv", locale = locale(encoding = "latin1"))

Read the wrong way, the accented letters appear as backslash x codes, the raw bytes R could not decode. With the latin one locale, the names come back perfectly: José, Zoë and Müller.

Pause and try#

Exercise: tidy these emails, then count customers per email domain

emails <- c(" Ana@Gmail.com", "ben@shop.com.au ", "CARLA@gmail.com",
            "dev@@shop.com.au", "eve@outlook.com", "no email")
tibble(email = str_to_lower(str_squish(emails))) |>
  mutate(valid = str_detect(email, "^[\\w.]+@[\\w.]+\\.[a-z]+$"),
         domain = str_extract(email, "(?<=@)[\\w.]+")) |>
  filter(valid) |>
  count(domain, sort = TRUE)

Four valid emails remain. Gmail has two customers, once the capitals were fixed, and outlook and the shop domain have one each. The double at sign and the text no email were rejected.

Bonus project: a messy inventory sheet#

Wide, inconsistent, and full of units.

inv_raw <- tribble(
  ~Item, ~`Adelaide stock`, ~`Perth stock`, ~`Unit cost`,
  " desk lamp", "12", "8", "$24.90",
  "Desk Lamp", "3", "-", "$24.90",
  "MONITOR ARM", "5", "11", "$89",
  "usb hub", "n/a", "20", "$19.5"
)
inventory <- inv_raw |>
  clean_names() |>
  mutate(item = str_to_title(str_squish(item)),
         unit_cost = parse_number(unit_cost)) |>
  pivot_longer(ends_with("stock"), names_to = "warehouse",
               values_to = "qty") |>
  mutate(warehouse = str_remove(warehouse, "_stock"),
         warehouse = str_to_title(warehouse),
         qty = parse_number(qty, na = c("-", "n/a"))) |>
  group_by(item, warehouse) |>
  summarise(qty = sum(qty, na.rm = TRUE),
            unit_cost = first(unit_cost), .groups = "drop") |>
  mutate(value = qty * unit_cost)
inventory

Six tidy rows, one per item and warehouse. The two lamp rows were combined, so Adelaide has fifteen lamps. Every count is a number and every value is quantity times cost. One thing to notice: the U S B hub in Adelaide shows zero, because summing nothing but a missing value with n a dot r m gives zero. Is the stock really zero, or just unknown? In a real report you would flag that row, just as we flagged the huge order.

inventory |>
  group_by(warehouse) |>
  summarise(items = n(), units = sum(qty),
            value = sum(value))

Adelaide holds three product lines, twenty units worth about eight hundred and eighteen dollars. Perth holds thirty nine units worth about one thousand five hundred and sixty eight dollars.

Recap: a cleaning checklist#

  1. Read with na codes, look with spec() and glimpse()

  2. Clean names, remove duplicates, check the key is unique

  3. Fix text (squish, case), numbers (parse_number), dates

  4. Flag suspicious values, decide on missing values

  5. Reshape to tidy, validate with stopifnot, save as RDS

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.