Data Wrangling: Import, Diagnose, Clean, Export
The graded work for this chapter is Data Wrangling in R (MC 501). Get the worksheet, the guide, and the rubric there.
Real data is messy. The Twitch dataset you’re about to work with has missing values, unreadable timestamps, messages that are twenty-three question marks long, and the information you most need sitting in a second table that the first one has no link to. This chapter teaches you how to find and fix these problems using R.
This is the single most practical R skill you’ll learn: every dataset needs cleaning before analysis, and the cleaning process is the same regardless of the topic.
Steps on this page
The Four-Step Wrangling Pipeline
Import → Diagnose → Clean → Export
Every data wrangling task follows this sequence. By the end of this chapter, you’ll have taken two raw tables and produced a single clean .RDS file ready for visualization and statistical testing.
Step 1: Import
First, load your packages and import the data:
library(tidyverse) # for data manipulation and visualization
library(v2v) # the course package: data, themes, and helpers
chat <- twitch_chat()
streams <- twitch_streams()Notice what is missing. There is no file path, no read_csv(), no download step. twitch_chat() and twitch_streams() reach into the v2v package, find the data that ships inside it, and hand it back. A new R user’s first encounter with data is usually a pile of path errors, and these two functions remove that entire category of problem.
chat is one row per chat message. streams is one row per snapshot of one stream at one moment. Let’s see what we’re working with:
dim(chat)
dim(streams)
names(chat)
names(streams)%>% Symbol?
The %>% is called a pipe. It takes the result from the left side and passes it to the function on the right side. Read it as “and then.” So streams %>% count(game) means “take streams and then count its games.”
You will also see |> in some tutorials. That is base R’s own pipe, and it does nearly the same thing. We use %>% because it comes with the tidyverse, which is what this course is built on.
Step 2: Diagnose
Before cleaning, you need to know what’s wrong. Think of this as a doctor’s exam: you check vital signs before prescribing treatment.
Check the Structure
glimpse(chat)Rows: 35,267
Columns: 5
$ id <int> 89, 551, 1033, 2094, 2803, …
$ channel <chr> "sodapoppin", "xqcow", "forsen", "sodapoppin", "xqcow", …
$ sender <chr> "madzee", "prometheanow", "spectre155", "itsjer", "laserfru…
$ message <chr> "???????????????????????", "TriEasy Clap TriEasy Clap TriE…
$ date <dbl> 1542578127023, 1542578135562, 1542578143610, 1542578157677…
glimpse(streams)Rows: 32,276
Columns: 6
$ id <int> 4, 10, 18, 61, 105, …
$ channel <chr> "sodapoppin", "xqcow", "forsen", "giantwaffle", "sodapoppin…
$ title <chr> "Hello truckers\n44835158804929_2115841973", "…", …
$ game <chr> "Marble It Up!", "Just Chatting", "Artifact", "Rocket Leag…
$ viewers <int> 27934, 19381, 15300, 4697, 28076, …
$ date <dbl> 1542578200214, 1542578200240, 1542578200273, 1542578200423…
Look at the data types:
<chr>= text (character)<int>= whole number (integer)<dbl>= number (double/decimal)<dttm>= date-time (you do not have one yet, but you will)
Two things in that output already tell you what the cleaning will involve. The date column is a run of enormous numbers marked <dbl>, not a date anyone can read. And there is no column anywhere saying how long a message is, or whether it came from a gaming channel. Those are variables your codebook named and the raw data does not contain.
Check for Missing Values
chat %>%
count(is.na(message)) # TRUE = the message is empty
streams %>%
count(is.na(game)) # TRUE = the snapshot has no categoryRun the same check on streams. In this sample the tables are almost complete: four chat messages are missing their text, and ninety-six stream snapshots are missing both title and game. A few missing values are normal. Columns with most values missing might need to be dropped entirely. And missing values in a key column, like game, will matter later, because a snapshot with no category cannot help you decide whether a channel is a gaming channel.
Check for Duplicates
nrow(chat) # total rows
chat %>%
distinct() %>%
nrow() # unique rows; the same number means no duplicatesCheck Categorical Variables
For text and categorical columns, check the unique values. count() tallies how often each value appears:
streams %>%
count(game, sort = TRUE)# A tibble: 61 × 2
game n
<chr> <int>
1 Art 5298
2 Fortnite 3682
3 Just Chatting 2474
4 Hearthstone 2157
5 Pokemon: Let's Go, Pikachu!/Eevee! 1967
6 League of Legends 1952
7 Heroes of the Storm 1473
8 Counter-Strike: Global Offensive 1346
9 Rocket League 1321
10 World of Warcraft 920
# ℹ 50 more rows
Sixty named categories plus a row of NA for the 96 snapshots with none, with a handful of games accounting for most of the snapshots and a long tail accounting for the rest. That shape matters: sixty is far too many lines to put on one chart, and Chapter 5 will have to do something about it.
count() is also a way to confirm the data is the corpus you expect. distinct() keeps one row for each different value in a column, and nrow() counts those rows:
chat %>%
distinct(channel) %>%
nrow()[1] 50
Fifty distinct channels, exactly the corpus this dataset is described as holding.
Check Numeric Variables
streams %>%
select(viewers) %>%
summary()Look for values that don’t make sense:
viewersshould be zero or a positive whole number, never negativedateshould be a count of milliseconds since 1970, so roughly 1.5 trillion for data collected in 2018. A value of 1542, or of 1.5 quintillion, means something went wrong upstream
Step 3: Clean
Now build what the analysis needs. The order matters: make the timestamps readable first, then derive the variables your codebook named, then join in the information that lives in the other table.
3a: Make the Timestamp Readable
The date column holds a count of milliseconds elapsed since midnight on the first of January, 1970. That reference moment is the Unix epoch, the zero point nearly all computers use to keep time. The number is precise and entirely unreadable. mutate() is the verb that fixes it, and lubridate’s as_datetime() does the conversion. Both tables get the new column, because the join in step 3c needs it on each side:
chat <- chat %>%
mutate(ts = as_datetime(date / 1000))
streams <- streams %>%
mutate(ts = as_datetime(date / 1000))date / 1000 divides by 1,000, because date counts milliseconds and R’s date-times count seconds. as_datetime(), from lubridate (which the tidyverse loads), then turns the seconds into a date and time, stored in a new ts column. Your own data will usually carry dates as text, such as 2024-03-01 14:22:05; lubridate reads those with ymd_hms(), ymd(), or mdy(), named for the order the text writes the year, month, and day.
chat %>%
select(date, ts) %>%
slice_head(n = 3)# A tibble: 3 × 2
date ts
<dbl> <dttm>
1 1542578127023 2018-11-18 21:55:27
2 1542578135562 2018-11-18 21:55:35
3 1542578143610 2018-11-18 21:55:43
A date-time function expects a count of seconds. The date column is a count of milliseconds, a thousand times finer. Hand it the raw number and every message lands tens of thousands of years in the future. date / 1000 converts milliseconds to seconds first. A missing / 1000 is the single most common way this step fails, and it fails quietly: you get dates, they are just absurd ones.
The column type changed too, from <dbl> to <dttm>. That new type is what makes the column useful. From a real date-time you can pull the hour of day, the day of week, or the calendar date, none of which can be read off the raw integer.
3b: Derive Message Length
message_length is a variable the codebook named and the data does not contain. str_length() counts the characters in a string:
chat <- chat %>%
mutate(message_length = str_length(message))
chat %>%
select(message, message_length) %>%
slice_head(n = 3)# A tibble: 3 × 2
message message_length
<chr> <int>
1 "???????????????????????" 23
2 "TriEasy Clap TriEasy Clap TriEasy Cla…" 441
3 "cmonBruh" 8
A single-word message at eight characters, a row of punctuation at twenty-three, and a block of copy-pasted text at 441 are all real Twitch chat. The distance between them is large, and that spread is the raw material of the analysis.
3c: Match Each Message to Its Stream
The information the research question turns on lives in the other table, so the chat and stream tables have to meet. The first join attaches to each message the stream snapshot taken at or before it, on the same channel. It takes two blocks. The first keeps the four stream columns the question needs and renames the snapshot’s time to snapshot_ts, so it cannot be confused with the message’s own ts. The second is the join itself:
snapshots <- streams %>%
select(channel, snapshot_ts = ts, game, viewers)
chat_streams <- chat %>%
left_join(snapshots, by = join_by(channel, closest(ts >= snapshot_ts)))
chat_streams %>%
count(no_snapshot = is.na(viewers))# A tibble: 2 × 2
no_snapshot n
<lgl> <int>
1 FALSE 35256
2 TRUE 11
Each message now carries the game and viewers of the latest snapshot before it, and snapshot_ts, the time of that snapshot. Eleven messages arrived before their channel’s first snapshot, so they carry NA. left_join() keeps every message, and join_by(channel, closest(ts >= snapshot_ts)) is a rolling join key: snapshots come every few minutes and messages every second, so the key is “the same channel and the nearest earlier snapshot,” not an exact match. The same two blocks work on any pair of tables where one holds events and the other holds readings taken now and then: change the table and column names and nothing else.
In the R Companion, AURA: Write R code, under R2 Data, writes these same as_datetime() and left_join() blocks, and the filter, select, mutate, and count steps, into your script with a comment above each block. Build each step by hand once first, as above, so you know what the generated code is doing.
3d: Label Gaming and Non-Gaming
Gaming or non-gaming is a property of the channel, fixed by what the channel mostly streams. So it takes three moves: find what each channel mostly streams, decide whether that counts as gaming, and attach the decision to every message from that channel. The course package has done the first two for all fifty channels and ships the result as a lookup table, one row per channel:
channels <- twitch_channels()
channels %>%
count(is_gaming) # channels, not messages# A tibble: 3 × 2
is_gaming n
<lgl> <int>
1 FALSE 5
2 TRUE 43
3 NA 2
main_game is the category a channel streamed most often across its snapshots. is_gaming is TRUE unless that category is on the non-gaming list, and channel_type says the same thing in words. Two judgment calls sit inside the table: which categories count as non-gaming, and where the audience bands (next section) are cut. Run ?twitch_channels to read both. They are decisions, not facts about the data, and a reader who disagrees needs to be able to see them. The package source, data-raw/build_channels.R, holds the dplyr pipeline that built the table.
chat_streams already has a game column, the category the channel was streaming when each message was sent. main_game is the channel’s usual category. The study labels by channel, so later chapters group by channel_type. If you ever group by category, use main_game; grouping by game runs without an error and gives different numbers.
The third move is the second join. A join brings columns from one table onto another by matching on a shared key, here the channel name. left_join() keeps every row of chat_streams and attaches the matching values:
analysis <- chat_streams %>%
left_join(channels, by = "channel")Always inspect a column you just derived:
analysis %>%
count(is_gaming)# A tibble: 3 × 2
is_gaming n
<lgl> <int>
1 FALSE 3457
2 TRUE 31309
3 NA 501
Two channels in the corpus streamed without ever having a category recorded, so the lookup table holds NA for them and the join left their messages with is_gaming set to NA. That is the correct outcome, not a bug. The data genuinely does not say whether those 501 messages came from gaming channels, and an honest NA records that. They will sit out the comparison rather than being guessed onto one side of it.
Twitch’s chat protocol writes channel names with a leading #, so the same channel can appear as #bobross in one source and bobross in another. Join two tables whose keys disagree like that and every row fails to match, silently, with no error message. The v2v data has already been normalized, but raw Twitch data would need that cleaning step first. When a join returns nothing, mismatched keys are the first thing to check.
3e: The Audience Bands
You’ll want a second categorical variable for Chapter 6’s chi-square test. Audience size is a good one, and the lookup table brought it in with the join: median_viewers is each channel’s typical audience, and viewer_band sorts it into three bands, small below 5,000 median viewers, medium up to 20,000, and large above. Count the channels in each band, then the messages:
channels %>%
count(viewer_band) # channels per band
analysis %>%
count(viewer_band) # messages per bandThe cutoffs (5,000 and 20,000 median concurrent viewers) are a decision the package made, not a fact about the data. Write them into your codebook. A reader who disagrees with the cutoffs needs to be able to see them, and ?twitch_channels is where they are written down.
3f: Factors, and Their Order
A factor is R’s way of storing a categorical variable. It remembers both the values and their labels, in an order you choose, which matters for visualization and statistical tests. channel_type and viewer_band arrived as factors, so count() lists them in the factor’s order rather than alphabetically:
analysis %>%
count(channel_type) # gaming, then non-gaming
analysis %>%
count(viewer_band) # small, medium, largeThe order matters. A factor made without levels = sorts its labels alphabetically, and the bands come out large, medium, small, a nonsense order on every chart you draw. When you make your own factor (the worksheet’s Task 5.2 turns your hand codes into one), factor(x, levels = c(...), labels = c(...)) sets the order and the labels in one call.
Step 4: Export
Save your cleaned data as an .RDS file. RDS is R’s native format: it preserves factor levels, data types, and everything else about your cleaned dataset.
write_rds(analysis, "data/workbook_analysis.RDS")
read_rds("data/workbook_analysis.RDS") %>%
nrow()This practice file has its own name so it never replaces twitch_analysis.RDS, the file your Data Wrangling worksheet saves and the next two worksheets read.
.RDS Instead of .csv?
When you save as CSV, R forgets which columns are factors and what their levels are. It also flattens your <dttm> timestamp back into text. When you save as RDS, everything is preserved. Since you just spent time converting timestamps and setting up factors, you do not want to lose that work. Always save your cleaned data as RDS. If you export from the R Companion, choose Save a table as an RDS file.
The Complete Pipeline (Summary)
Here’s the entire wrangling process in one code block, without the diagnostic checks:
library(tidyverse)
library(v2v)
chat <- twitch_chat()
streams <- twitch_streams()
chat <- chat %>% # readable time, message length
mutate(
ts = as_datetime(date / 1000),
message_length = str_length(message)
)
snapshots <- streams %>%
mutate(ts = as_datetime(date / 1000)) %>%
select(channel, snapshot_ts = ts, game, viewers) # four columns, snapshot time renamed
chat_streams <- chat %>%
left_join(snapshots, by = join_by(channel, closest(ts >= snapshot_ts))) # nearest earlier snapshot
channels <- twitch_channels() # one row per channel: category, label, audience band
analysis <- chat_streams %>%
left_join(channels, by = "channel") # join key: channel
write_rds(analysis, "data/workbook_analysis.RDS")A glimpse() of the finished table shows what the transformations bought you. The first ten columns are your own transformations; the join with twitch_channels() adds the last five:
Rows: 35,267
Columns: 15
$ id <int> 89, 551, 1033, 2094, 2803, 10406, 16104, 22571, 31555, …
$ channel <chr> "sodapoppin", "xqcow", "forsen", "sodapoppin", "xqcow",…
$ sender <chr> "madzee", "prometheanow", "spectre155", "itsjer", "lase…
$ message <chr> "???????????????????????", "TriEasy Clap TriEasy Clap T…
$ date <dbl> 1.542578e+12, 1.542578e+12, 1.542578e+12, 1.542578e+12,…
$ ts <dttm> 2018-11-18 21:55:27, 2018-11-18 21:55:35, 2018-11-18 2…
$ message_length <int> 23, 441, 8, 12, 206, 37, 6, 7, 4, 7, 3, 4, 12, 21, 3, 7…
$ snapshot_ts <dttm> NA, NA, NA, NA, NA, 2018-11-18 21:56:40, 2018-11-18 21…
$ game <chr> NA, NA, NA, NA, NA, "Artifact", "Marble It Up!", "Rocke…
$ viewers <int> NA, NA, NA, NA, NA, 15300, 28076, 4703, 19239, 28550, 2…
$ main_game <chr> "Hand Simulator", "Just Chatting", "The Elder Scrolls V…
$ is_gaming <lgl> TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE…
$ channel_type <fct> gaming, non-gaming, gaming, gaming, non-gaming, gaming,…
$ median_viewers <dbl> 22944, 16176, 10163, 22944, 16176, 10163, 22944, 4867, …
$ viewer_band <fct> large, medium, medium, large, medium, medium, large, sm…
The rows keep the chat table’s order, so the first rows are the earliest messages, which arrived before their channels’ first snapshot; that is why snapshot_ts, game, and viewers open with NA. The table is now tidy: each row is one observation, one chat message; each column is one variable; and everything the analysis needs sits in one place. The unreadable integers have become timestamps. Message length and gaming status, named in the codebook and absent from the raw data, are now columns. The chat and stream tables, once disconnected, are joined twice: once to the snapshot nearest each message, once to the channel’s label.
None of this was analysis. Not one result has been computed. But every figure in Chapter 5 and every test in Chapter 6 comes out of this table, which is why the care spent building it is not optional. A wrangling mistake does not announce itself. It travels quietly into every chart downstream.
Try It Yourself
These exercises directly prepare you for the Data Wrangling [R] assignment:
Diagnose another column: Run
summary()on theviewerscolumn ofstreams, the way the numeric check above does. What is the largest value? What is the median? Why is the gap between them so large?Read the judgment calls: Run
?twitch_channelsand find the non-gaming list and the two audience cutoffs. Pick one category you would have placed differently, and write one sentence for your codebook saying how the study’s numbers would move if you did.Check your joins: After running the full pipeline, run this. Which channels came back
NA, and what does the stream table say about them?analysis %>% filter(is.na(is_gaming)) %>% count(channel)Then run the same three lines with
is.na(viewers)in thefilter()line, for the messages the stream join could not place.Run the full pipeline: Starting from
twitch_chat(), apply all four steps to produce a clean.RDSfile. Verify it loads correctly withread_rds()and thatnrow()still reports 35,267.
For your own data, you’ll follow this exact pipeline, but with your file and your variables. The assignment uses the Twitch dataset as practice. Your White Paper uses your own coded data. Same skills, different dataset.
Your data will almost certainly need a derived variable, the way message_length had to be computed rather than collected, and it may well need a join, the way the gaming label had to be pulled from a second table. Those two moves are most of what wrangling is.