Wrangling Lab

S22 · Chapter 11

Today’s Agenda

  • Match each message to the stream snapshot taken just before it
  • Load the channel labels: what each channel streams, and how big its audience is
  • Join two tables on a shared key
  • Inspect the rows a join leaves behind
  • Write one pipeline that rebuilds the whole table

Finishing the Wrangle

  • Tuesday we built readable timestamps and message length
  • Today we build the gaming label, which the example question depends on
    • The stream join, the gaming label, and the rows a join leaves unlabeled
    • Then one pipeline you can rerun from scratch
  • Every step today is plain tidyverse, written the way you will write it on your own data
  • In VS Code’s Explorer, open 11-wrangling-data.qmd, the copy you saved in your workspace’s top folder. We continue from Part 4

What Is Still Missing

  • ts exists, and message_length exists
  • Nothing says whether a message came from a gaming channel
    • That information sits in the stream table, which is separate from the chat table
    • So one side of the example comparison is still undefined
  • Your own data may need a column from a second table; a join is how you add it
  • Joins often go wrong the first few times you write them, and R often gives no error when one does

Gaming Is a Property of the Channel

  • Whether a channel is a gaming channel is fixed by what it mostly streams
    • Bob Ross streams painting, so every message in that channel is non-gaming
  • So the channels are classified first, then the label is attached to every message
    • Find what each channel mostly streams
    • Decide whether that category counts as gaming
    • Attach the decision to every message from that channel

The course package did the first two steps for all fifty channels. The join is yours.

Step 1, Match Each Message to Its Stream

  • Type these two blocks into the worksheet’s Task 4.1 chunk, then run them
  • First, keep only the stream columns the question needs, and rename the snapshot’s time so it cannot be confused with the message’s time
snapshots <- streams %>%
  select(channel, snapshot_ts = ts, game, viewers)
  • select() keeps four columns and renames ts to snapshot_ts on the way
  • Both tables need Tuesday’s ts column

Step 1, Match Each Message to Its Stream (cont.)

chat_streams <- chat %>%
  left_join(
    snapshots,
    by = join_by(channel, closest(ts >= snapshot_ts))
  )
  • left_join() keeps every message and attaches the game and viewers of the latest snapshot taken at or before it, on the same channel
  • join_by(channel, closest(ts >= snapshot_ts)) is the key: same channel, nearest earlier snapshot
  • On your own data, the same two blocks work with your table and column names

Step 1, Check the Result

chat_streams %>%
  count(no_snapshot = is.na(viewers))
  no_snapshot     n
1 FALSE       35256
2 TRUE           11
  • Eleven messages arrived before their channel’s first snapshot, so they get NA (missing)

A Rolling Join, Named

Rolling join: a join whose key matches the nearest value instead of an exact one. Example: each message takes the latest snapshot at or before its own time, because no snapshot shares a message’s exact second.

  • closest(ts >= snapshot_ts) is the rolling part: the snapshot time closest to the message time, without passing it
  • It is needed because snapshots come every few minutes and messages every second
  • More detail: Chapter 11, Matching each message to its stream

Step 2, Load the Channel Labels

  • Task 4.2: AURA: Write R code, R2 Data, Label each channel by its top category writes this step
channels <- twitch_channels()

channels %>%
  count(is_gaming)
  is_gaming     n
1 FALSE         5
2 TRUE         43
3 NA            2
  • A lookup table: one row per channel, 43 gaming, 5 non-gaming, and 2 the data cannot place

Step 2, Your Own Lookup Table

  • twitch_channels() loads the example lookup table, built once for the course
  • Your own lookup table is a file you read, the same way as any other table
channels <- read_csv("data/channels.csv")
  • One row per thing you label (a channel, an account, an outlet), one column for the key, and one column per label

Exercise: Trace a Channel With No Category

Two channels have no game recorded in any snapshot. Use Chapter 11, Labeling gaming and non-gaming.

  • What does channels hold for such a channel in main_game? In is_gaming?
  • After the join in Step 4, what will that channel’s messages show in is_gaming? Answer in one word
  • When its messages are analyzed later, should R guess a label, drop the messages, or flag them? Give one reason

Step 3, Two Judgments Inside the Table

  • Which categories count as non-gaming is a judgment, not a fact in the data
    • Art, ASMR, Beauty & Body Art, Creative, Food & Drink, IRL, Just Chatting, Makers & Crafting, Music, Music & Performing Arts, Science & Technology, Sports & Fitness, Talk Shows & Podcasts, Travel & Outdoors
    • Every other category counts as a game
  • Where the audience bands are cut is a second judgment
    • small below 5,000 median viewers, medium up to 20,000, large above
  • Run ?twitch_channels to read both, so a reviewer can check them

Step 3, How the Table Was Built

  • main_game is the category a channel streamed most often across its snapshots
    • Bob Ross streams Art, so is_gaming is FALSE for every one of his messages
  • median_viewers is the channel’s typical audience, and viewer_band cuts it into the three bands
  • The package source, build_channels.R, holds the dplyr pipeline that built it: count the snapshots per channel and category, keep each channel’s most frequent one, take the median viewers, cut the bands
  • More detail: Chapter 11, Labeling gaming and non-gaming

Step 4, Join the Label Onto the Messages

  • The R Companion writes this join: AURA: Write R code, then R2 Data, then Join the channel labels onto the messages
    • Change chat_streams <- at its start to analysis <-
analysis <- chat_streams %>%
  left_join(channels, by = "channel")
  • left_join() keeps every row of chat_streams, attaches each channel’s five label columns, and names the result analysis

Step 4, Join the Label Onto the Messages (cont.)

Join: putting two tables together by matching a shared key, so each row picks up the other table’s columns. Example: every message picks up its channel’s main_game and is_gaming.

  • by = "channel" names the key column both tables share
  • channels is the lookup table: one row per channel, looked up by the join

Joining Your Own Tables

  • For your own tables, the R Companion’s Join two tables by a shared column writes a join like this one
    • It also adds two checks on the result
  • Every join needs a key column that both tables share

Joins Fail When the Keys Do Not Match

Key: the column two tables share, which says which row in one goes with which row in the other. Example: channel, which reads bobross in both tables.

  • A join is only as good as the match between its keys
    • Twitch’s chat protocol writes channel names with a leading “#”
    • So one source says #bobross and another says bobross
  • Keys that disagree fail on every row, and R reports no error
  • The example data in v2v has matching keys; raw Twitch data does not
  • Check the key column in your own source before every join

Always Inspect What You Derived

analysis %>%
  count(is_gaming)
  is_gaming     n
1 FALSE      3457
2 TRUE      31309
3 NA          501
  • Running count() on a new column is the quickest check there is
  • Here it shows a third value, NA, alongside TRUE and FALSE

The 501 Unlabeled Messages

Missing value (NA): a cell with nothing in it, which R prints as NA. Example: the 501 messages from the two channels with no recorded category.

  • Two channels never had a category recorded
    • Every snapshot of those channels had a missing game, so there was no most frequent category
    • channels holds NA for them, so the join left their messages as NA
  • That is the correct outcome, not a bug
  • The data does not say whether those channels are gaming, so their 501 messages are left out of the comparison

The Whole Wrangle in One Block

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)
channels <- twitch_channels()
analysis <- chat %>%
  left_join(
    snapshots,
    by = join_by(channel, closest(ts >= snapshot_ts))
  ) %>%
  left_join(channels, by = "channel")
  • Two transformations, then two joins, rebuild the 15-column table in one run, and every line is plain tidyverse

The Whole Wrangle (cont.)

  • This block shows the shape only. Do not run it in your worksheet: it skips Part 5, so the table it builds has no codes

Saving the Table

  • The R Companion writes the save line: AURA: Write R code, then R2 Data, then Save a table as an RDS file
write_rds(analysis, "data/twitch_analysis.RDS")
  • write_rds() saves the table as an RDS file, R’s own data file, with every column type intact
    • Worksheet Part 7 saves it, and Describing Data reads that file

What the Table Has Become

Rows: 35,267   Columns: 15
$ id, channel, sender, message, date: the five raw columns
$ ts             <dttm> 2018-11-18 21:55:27, …
$ message_length <int> 23, 441, 8, …
$ snapshot_ts    <dttm> NA, NA, NA, …
$ game           <chr> NA, NA, NA, …
$ viewers        <int> NA, NA, NA, …
$ main_game      <chr> "Hand Simulator", "Just Chatting", …
$ is_gaming      <lgl> TRUE, FALSE, TRUE, …
$ channel_type   <fct> gaming, non-gaming, gaming, …
$ median_viewers <dbl> 22944, 16176, 10163, …
$ viewer_band    <fct> large, medium, medium, …
  • The table is now tidy: one row per observation, one column per variable
  • The rows stay in message order, so the first rows are the earliest messages, from before their channels’ first snapshot: that is why snapshot_ts and viewers open with NA

Your Thirty Codes

Factor: R’s way of storing a category, with its labels in an order you choose. Example: viewer_band stored as small, medium, large.

  • Part 5 reads your coding sheet back: read_csv(), then clean_names()
  • factor() turns 0 and 1 into labeled groups, commentary and reaction
  • left_join(codes, by = "id") attaches them: the coding sheet’s id is the chat id
  • Every other message gets NA on reaction_only, and that is correct

Common Errors Today

  • The join returns all NA: the keys do not match, so check for a leading “#”
  • object 'snapshot_ts' not found: the select() that renames the snapshot time never ran, so make snapshots first
  • object 'channels' not found: R has no object (no named result) called that yet: you ran the join before loading the lookup table
  • could not find function "twitch_channels": your v2v is older than 0.3.8: run AURA: Check my setup, then Install what is missing
  • A worksheet that will not render: it depends on a step you ran in the terminal but never wrote into the worksheet

Any Other Error

  • Select the error R printed in the terminal, then press Ctrl+C (Cmd+C on a Mac) to copy it
  • Press Ctrl+Shift+P (Cmd+Shift+P on a Mac) and run AURA: Explain an R error: the copied error is filled in for you
The R Interactive terminal at the bottom of VS Code. After the line summary(message_length), R printed Error: object 'message_length' not found.

What Explain an R Error Shows

The explanation page that opens beside the script, headed object ... not found. Under From your message it quotes object 'message_length' not found. Why this happens says R has no value stored under that name: the line that creates it never ran, the name is misspelled, or a text value was typed without quotation marks. What to do lists three checks: run the line that creates it first, check the spelling and capital letters, and put text in quotation marks.
  • The explanation opens beside your script: why the error happens, then what to do

Checkpoint

You should now have:

  • A channels lookup table, one row per channel, with main_game, is_gaming, channel_type, median_viewers, and viewer_band
  • An analysis table of 16 columns: the 15 shown earlier plus reaction_only
  • A count(is_gaming) result you have actually looked at
  • Worksheet Parts 4 to 7 filled: the labels joined on, your thirty codes joined on, data/twitch_analysis.RDS saved
  • A worksheet that rebuilds all of it from the raw data when you render it

Before Next Time

  • Render your worksheet: save it, then press Ctrl+Shift+K (Cmd+Shift+K on a Mac), as in Render a Quarto Document
    • Rendering runs every chunk from the top in a fresh R session, so a missing step shows up as an error
  • Check it against the Data Wrangling risks guide
  • Step by step: Wrangle the Data with Write R Code, with its walkthrough video
  • Comment your wrangling decisions in the worksheet
    • A reviewer will ask why you excluded what you excluded
    • A comment the R Companion writes says what a step does. Your comment says why you chose it

Before Next Time (cont.)

Questions, Comments, or Concerns?