Tidy Data Patterns
Split Keys
Columns Hidden in Text
Compact labels often hide multiple variables. Splitting a key turns those variables into separate columns.
Program
Play the script to split region-group codes, choose a region, and total its counts.
split_keys.R
raw <- data.frame(code = c("north_A", "north_B", "south_A"), count = c(3, 5, 4))
parts <- do.call(rbind, strsplit(raw$code, "_", fixed = TRUE))
tidy <- data.frame(region = parts[, 1], group = parts[, 2], count = raw$count)
region_index <-
region <- c("north", "south")[region_index]
total <- sum(tidy$count[tidy$region == region])
cat(total, "\n", sep = "")
raw <- data.frame(code = c("north_A", "north_B", "south_A"), count = c(3, 5, 4))
parts <- do.call(rbind, strsplit(raw$code, "_", fixed = TRUE))
tidy <- data.frame(region = parts[, 1], group = parts[, 2], count = raw$count)
region_index <-
region <- c("north", "south")[region_index]
total <- sum(tidy$count[tidy$region == region])
cat(total, "\n", sep = "")
encoded key
`code` combines two variables in one text field.
strsplit
`strsplit(..., fixed = TRUE)` splits each code at the underscore.
separate columns
`region` and `group` become explicit columns for filtering and summaries.