Chapter 11: Wrangling the data
Listen in Dr. Leith’s voice
The chat table you loaded in Chapter 9 cannot answer your research question. Not yet. The study asks whether chat behaves differently on gaming and non-gaming channels, and it operationalizes that through message length. But look at the table. There is no column for message length. There is no column saying whether a message came from a gaming channel or a non-gaming one. The timestamps are unreadable runs of digits. And the information that would settle the gaming question is not even in the chat table; it sits in a separate stream table that the chat table has no link to.
This is the ordinary situation at this stage of a study, and closing the gap is the work of this chapter. Data wrangling is the process of turning the data you collected into the data you can analyze: reshaping it, cleaning it, deriving the variables your codebook named, and joining separate tables into one. It is unglamorous, it is rarely mentioned in the published paper, and it is most of the work. A wrangling chapter looks like a sequence of small technical steps. What it is actually doing is building the table that every later result depends on.
The verbs of data wrangling
The tidyverse handles wrangling through a small set of functions, each of which does one clear thing to a data frame, R’s name for a table of rows and columns. They are usually called the dplyr verbs, after the package they live in, and five of them carry most of the work.
filter() keeps rows that meet a condition and drops the rest. To look at only Bob Ross’s messages:
chat %>% filter(channel == "bobross")select() keeps or drops columns:
chat %>% select(channel, sender, message)mutate() adds a new column, or changes an existing one, computed from the columns already there. arrange() reorders the rows by a column’s values. And group_by() together with summarize() collapses many rows into one per group, which is how you compute a per-channel or per-game figure.
The reason these verbs combine so well is a shared design: each one takes a data frame and returns a data frame. That is what lets the pipe, %>% (read it as “and then”), string them into a sequence, the output of one verb flowing in as the input of the next. A wrangling pipeline is just verbs chained this way, each step a small readable transformation, the whole chain carrying the data from raw to ready. The rest of this chapter is four such transformations.
The wrangling script as a methods section. A wrangling script is a documented transformation chain: a sequence of decisions, each recorded in version-controlled code, that connects raw data to analysis-ready data. Every mutate(), filter(), and group_by() is a methodological decision. You decided which cases to exclude and why. You decided how to handle missing values. You decided how to aggregate timestamp data into time windows. When a reviewer asks “how did you handle cases where the streamer’s username appeared in the chat?”, the answer is in the wrangling script, but only if the script is version-controlled and decision points are commented. For your own study, identify three wrangling decisions a reviewer might challenge, and for each add a comment stating the decision rule and its justification.
The R Companion, the course’s extension for VS Code, writes code blocks like this chapter’s from a menu: run AURA: Write R code and look under R2 Data.
Step by step:
Making the timestamp readable
Start with the timestamps, because Chapter 9 already flagged them. The date column is a column of very large numbers, and Chapter 8 classified it as interval data with a catch: the number is not a date in any form a person can read.
What the number actually holds is 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, and counting from it is how a timestamp becomes a single integer. The integer is precise and entirely unreadable. Turning it back into a date is a conversion, mutate() is the verb for it, and as_datetime() does the converting. It comes from lubridate, the tidyverse package for dates, which library(tidyverse) loads. Both tables get the new column, named ts, because the join later in this chapter needs it on each side:
chat <- chat %>%
mutate(ts = as_datetime(date / 1000))
streams <- streams %>%
mutate(ts = as_datetime(date / 1000))as_datetime() expects a count of seconds, but the date column is a count of milliseconds, a thousand times finer, so the division by 1,000 comes first. Hand it the raw number and it will place every message tens of thousands of years in the future. It is a small arithmetic step and the single most common way the conversion fails.
Your own data will carry its dates in some other form, usually as text, and lubridate has a reader for each: ymd_hms() reads 2024-03-01 14:22:05, and mdy() reads 3/1/2024. Each reader is named for the order in which the text writes the year, month, and day. The step is the same mutate() with a different reader inside it. The v2v package keeps clean_dates() as a deprecated shortcut for work already written with it.
The result is a real date-time. Setting date and the new ts side by side shows the transformation:
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
The same instant, now legible: the evening of the 18th of November, 2018. The column type has changed too, from <dbl>, an ordinary number, to <dttm>, a date-time. 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, the calendar date, none of which can be read off the raw integer. Chapter 12 will use exactly that to chart how chat volume rises and falls across the hours of the day.
Measuring message length
The second transformation creates a variable the codebook named but the data does not yet contain. Message length, the character count of a message, is mutate() again, this time with str_length(), which 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
message_length is a ratio variable, in the Chapter 8 sense: a true zero, equal intervals, a count you can average and compare. The three values above also preview something. A single-word message of eight characters, a row of punctuation at twenty-three, and a block of copy-pasted text at 441 are all real Twitch chat, and the distance between them is large. That spread is the raw material of the study, and Chapter 12 will look hard at its shape.

Matching each message to its stream
The information the central research question turns on lives in the other table, so the third transformation is a join. It attaches to each message the stream snapshot taken at or before it, on the same channel: the game the channel was streaming at that moment, the viewers watching, and snapshot_ts, the time of that snapshot. Two blocks do it. The first keeps the four stream columns the join needs and renames the snapshot’s time to snapshot_ts, so the message’s own ts keeps its name. The second is the join.
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
Eleven messages arrived before their channel’s first snapshot, so they carry NA for the stream columns. left_join() keeps every message, and join_by(channel, closest(ts >= snapshot_ts)) is the key. It is a rolling join: snapshots come every few minutes and messages every second, so the key is not an exact match but “the nearest earlier snapshot on the same channel.” Both tables needed the ts column for that, which is why the conversion above ran on streams as well as chat. The same two blocks join any pair of tables where one records moments and the other records states, with your own table and column names in place of these. The v2v package keeps join_chat_streams() as a deprecated shortcut for work already written with it.
Labeling gaming and non-gaming
Every message also needs a label: did it come from a gaming channel or a non-gaming one? The snapshot’s game is not that label. A channel that mostly streams games can spend an afternoon in Just Chatting, and the study classifies channels, not moments. Building the channel label takes more work than the last three steps.
Gaming or non-gaming is best understood as a property of the channel, fixed by what the channel mostly streams. Bob Ross’s channel streams painting; it is a non-gaming channel, and every message in it is a non-gaming message. So the label is built in three steps: 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 does the first two steps and hands back the result as a table, because both steps need more dplyr than this chapter teaches. twitch_channels() returns one row per channel. The two columns this chapter needs are main_game, the category the channel streamed most often across the week, and is_gaming, whether that category is a game; the other three (channel_type, median_viewers, and viewer_band) are the same split as words and the channel’s audience size, which the course worksheet uses.
channels <- twitch_channels()
channels %>%
select(channel, main_game, is_gaming)# A tibble: 50 × 3
channel main_game is_gaming
<chr> <chr> <lgl>
1 704cb1fgnty <NA> NA
2 animeilluminati Tekken 7 TRUE
3 asmongold World of Warcraft TRUE
4 avew1004 Hearthstone TRUE
5 bobross Art FALSE
# ℹ 45 more rows
The first row already shows a channel with no category at all; the end of this section returns to it.
Two judgments sit inside that table, and a reader of the study should be able to see both. The first is what “mostly streams” means: here it is the modal category, the one that appears in the most snapshots for that channel, with ties broken by taking the first. The second is which categories count as non-gaming. Twitch sorts streams into categories, and some of those categories are not games: painting under Art, unstructured talk under Just Chatting, music, cooking, and a dozen others. The package keeps that list, and twitch_channels() prints the dplyr it stands for the first time you call it, so you can read the list and the slice_max() step that picks the mode. Chapter 12 returns to what is on it. Whether you write the rule yourself or take it from a package, the rule is a choice, and a methods section names it.
main_game is a separate column from game because chat_streams already has a game column, the category at each message. Chapters 12 and 13 group by main_game whenever they mean the channel’s category; grouping by game instead runs without an error and produces different numbers.
The third step is the second join. A join brings columns from one table onto another by matching on a shared key, here the channel name. A left_join() keeps every row of chat_streams and attaches the matching main_game and is_gaming values to it:
chat_streams <- chat_streams %>%
left_join(channels, by = "channel") # join key: channel, the column both tables shareThe comment on that line is not decoration. A join is the step a reader is most likely to question, and a comment naming the key is how the script answers before the question is asked. A join is only as good as the match between its keys, and that is worth a word of warning. 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. The v2v fixture has already normalized this, the “#” stripped before the data ever reached you, but raw Twitch data would need that cleaning step first. When a join returns nothing, mismatched keys are the first thing to check.
One result of the join deserves attention. Always inspect a column you just derived:
chat_streams %>%
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: every one of their stream snapshots had a missing game. With no categories at all, there is no modal category, so their rows in channels carry NA for main_game and is_gaming, and the left_join() carried that NA onto every one of their messages. 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 the study cannot classify them. They will sit out the gaming comparison rather than being guessed into one side of it.
Adding the variable you coded by hand
Three of the study’s variables are now columns, and all three were computed. The fourth, message target, cannot be computed. It is the variable the codebook exists for, the one a coder assigns by reading each message, and it reaches R by a different route.
The coding happens outside the script, in a coding sheet: a spreadsheet with one row per sampled message. Chapter 10 drew the sample with slice_sample(), and the sample carries each message’s id. Keep that column: it is the key that will carry the codes back onto the table. The sheet starts from the sample, keeping the key and what the coder needs to read:
coding_sample %>%
select(id, channel, message) %>%
write_csv("data/coding-form.csv")The coder adds the code column by hand, in a spreadsheet or in the R Companion’s data viewer, and never changes the three columns that came from R. Code the messages, save the sheet as a CSV in data/derived/ with two columns, id and message_target, and read it in, as below. The course worksheet runs this same route under its own names: its coding sheet is data/coding-form.csv, and its hand-coded variable is reaction_only. If you code in the data viewer of the R Companion (the AURA Lab R Companion icon on VS Code’s left edge; the command is AURA: Open the data viewer) instead, it saves your codes in data/derived/ and never changes the original, and its Insert rebuild code button writes the lines that bring them back as coded_data.
codes <- read_csv("data/derived/message_target_codes.csv")
chat_streams <- chat_streams %>%
left_join(codes, by = "id") # join key: id, the message's unique labelTwo things are true of the result, and both are correct. Every message you coded now carries its code. Every message you did not code carries NA for message_target, because the variable exists only where a coder assigned it, and the thousands of messages outside the sample were never coded. A count makes that visible:
chat_streams %>%
count(message_target)The NA row will be by far the largest. That is the shape of a hand-coded variable in a large dataset: a column that is full for the sample and empty everywhere else, and an analysis of that variable runs on the sample alone. The same route carries any hand-coded variable, from any material. Code it in a sheet keyed on the unit’s identifier, save it where the script can read it, and join it on the key.
The analysis-ready table
Two transformations and three joins, run in sequence, have rebuilt the chat table:
chat <- twitch_chat() %>%
mutate(
ts = as_datetime(date / 1000),
message_length = str_length(message)
)
snapshots <- twitch_streams() %>%
mutate(ts = as_datetime(date / 1000)) %>%
select(channel, snapshot_ts = ts, game, viewers)
analysis <- chat %>%
left_join(snapshots, by = join_by(channel, closest(ts >= snapshot_ts))) %>% # nearest earlier snapshot
left_join(channels, by = "channel") %>% # join key: channel
left_join(codes, by = "id") # join key: id
write_rds(analysis, "data/twitch_analysis.RDS")The table now has a name, analysis, and the last line saves it. write_rds() writes an R object to disk exactly as it is, column types included, so the date-time column is still a date-time when the file is read back. A CSV would lose that, and the next chapter would have to redo the conversion. Chapters 12 and 13 begin by reading this one file with read_rds(), which is why the name matters: twitch_analysis.RDS is the single handoff from wrangling to analysis, and it is the file the Data Wrangling assignment asks for.
The join also brought two columns the course worksheet uses: viewer_band, each channel’s audience band (small, medium, large), and channel_type, the gaming split written as the words “gaming” and “non-gaming”. Chapters 12 and 13 use is_gaming; the worksheets and the R Companion use channel_type, which holds the same split.
Everything above happens in the script. Nothing is done by hand in the console and nothing is edited in the spreadsheet after the codes are saved, because a change made by hand is a change the script cannot reproduce. A step built with R2 Data in the R Companion’s Write R code meets this test, because the menu writes commented code into the script rather than changing the data in place. The test is cheap: render the file (in VS Code, Quarto: Preview), which runs every chunk from the top in a fresh R session, and see whether the same file comes out. If it does not, a step is missing from the script, and finding it now is far cheaper than finding it in December.
A final glimpse() shows what the table has become, before the hand-coded column is joined:
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 order of the raw chat table, so the first rows shown are the first messages of the week, from sodapoppin, xqcow, and forsen. Their snapshot_ts, game, and viewers print NA because they arrived before their channel’s first snapshot: they are among the eleven unmatched messages the count above reported, not a broken join. The last three columns came from channels and are the ones the course worksheet uses.
This is what wrangling was for. The table is now tidy, in the precise sense the term carries in data science (Wickham, 2014): each row is one observation, a single chat message; each column is one variable; and everything the study needs sits in this 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, and so is the hand-coded message target for the sampled messages. 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 a single result has been computed. But every result that follows, every figure in Chapter 12 and every test in Chapter 13, will be computed from 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 and every statistic downstream. The reward for getting this chapter right is that nothing later has to be unwound.
Tidy data as the target state. Wickham’s tidy data principles (one observation per row, one variable per column, one value per cell) are not just a preference. They are the structural assumption that every tidyverse function makes about its inputs and produces about its outputs. Wickham (2014) defines the target in one sentence:
“Tidy data is a standard way of mapping the meaning of a dataset to its structure.”
Wickham (2014, p. 4)
Wrangling that produces tidy data is wrangling that can be audited: the structure itself is a transparency claim.
Never overwrite raw data. Keep what you collected in data/raw/ exactly as it arrived. Your wrangling script reads from it and writes new files elsewhere, such as data/twitch_analysis.RDS or a file in data/derived/, never back into data/raw/. The course scaffold keeps data/raw/ off GitHub, so the copy on your computer is the only one: keep a backup. This separation means you can rebuild the processed dataset from scratch by re-running the script against the unchanged raw data. To test it on your own study, render the script in a fresh session: if it does not produce the same file without your help, find the step it depends on that it does not write down.
Looking ahead
The data is tidy and the variables exist. The next move is to look at them. Chapter 12 turns the analysis-ready table into figures: how chat volume moves across the hours of the day, how viewership splits across game categories, and how the distribution of message length compares between gaming and non-gaming channels. It is the chapter where the study’s central question finally meets a picture of the answer.
References
Wickham, H. (2014). Tidy data. Journal of Statistical Software, 59(10), 1-23. https://doi.org/10.18637/jss.v059.i10