# Cleaning Messy Real-World Data in R ----
# Video 7 of R Programming: Zero to Expert.
# Import, inspect, fix and validate data that fights back.

# Setup ----

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

# 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

spec(orders0)

names(orders0)

glimpse(orders0)

problems(orders0)

# 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

# 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()

# 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)

# Step 4: remove duplicate rows ----

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

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

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

# Step 5: fix text columns ----

orders3 |> distinct(customer_name)

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)

# Step 6: turn text into numbers ----

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

parse_number(orders4$amount)

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

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

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

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))

# Step 7: dates in several formats ----

orders5$order_date

ymd(orders5$order_date)

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

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))

# 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))

# Two date traps from Excel ----

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

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

# 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

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

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)

# Step 9: missing values ----

colSums(is.na(orders7))

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

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

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

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

# 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)

# 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"

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"))

# 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)

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))

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

# 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")

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

# Padding IDs and fixing codes ----

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

# 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)

# 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")

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

# 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

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

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

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

# 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"))

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

# 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.]+")

# 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

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

# Reading Excel files ----

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

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

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

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

# 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

str(customers)

customers |>
  unnest_longer(orders, keep_empty = TRUE)

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

toJSON(sales_long, pretty = TRUE)

# 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)

dq_report(orders8)

# 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

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

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

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

# 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"))

# 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)

# 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

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

# 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