Wrangling the Data [R]

Week 11 · Chapter 11

Today’s Agenda

  • The Twitch job: three worksheets, one study
  • The gap between the data you have and the question you asked
  • Four transformations, built one at a time
  • Joins, and how they fail without an error message
  • Your wrangling script as a methods section

What We Build Today

  • One analysis-ready table, built from the raw example chat and stream tables
    • A readable timestamp, a message length, a stream join, and a gaming label
  • Weeks 12 and 13 compute everything from this table
  • Your script records the steps your Methods section reports
  • The example data is the shared practice case. You run the same steps on your own source
  • Wrangling is slow, repetitive work, and researchers spend most of their data time on it

Get the Worksheet

Today’s steps, as a worksheet with blanks: Data Wrangling worksheet

  • Click the link: your browser saves 11-wrangling-data.qmd in your Downloads folder
  • Move it into your workspace’s top folder, next to README.md: Put a Worksheet in Your Workspace

The Twitch Job

Hand-coding: reading each message yourself and recording its value by a written rule. Example: LULW alone is coded 1, a reaction; BIG TREE is coded 0, commentary.

  • Data Wrangling, Describing, and Inferencing are three parts of one Twitch study
  • Each part is a worksheet: routine code written, core steps left blank
  • Part 0: hand-code thirty messages; Inferencing tests that variable
  • The worksheet marks where your three reviewer-facing comments go

Data Wrangling worksheet · Data Wrangling risks guide

The Gap You Are Closing

  • The example study asks whether the two kinds of channel differ
    • It measures that difference through message length
  • Neither column exists in the loaded table
    • There is no message length column and no gaming label column
  • The timestamps are long numbers that no person can read as dates
  • The gaming information is in the other table entirely
  • Your own data will probably lack some columns your question needs; the same four moves build them

Variables, Revisited

Variable: something about a case that can change from one case to the next, where a case is one thing you study, such as one chat message.

  • The example study’s two variables are the gaming label and message length
  • An analysis-ready table gives each variable its own column and each case its own row

Data Wrangling, Defined

Data wrangling: getting data into a form you can analyze, by tidying it (one row per case, one column per variable) and transforming it (keeping rows, adding columns, summarizing, joining tables). Example: turning the chat table’s timestamp digits into dates and adding a message length column.

  • It is most of the work, and the paper rarely describes it
  • Every result in Weeks 12 and 13 depends on the table it builds

Packages and the Tidyverse

Package: a bundle of functions, data, and help pages that adds to what R can do on its own. Example: the course package, v2v, adds the example Twitch data.

Tidyverse: a collection of R packages for data science that share one design and are built to work together. Example: library(tidyverse) loads its core packages at once, including dplyr for tables, lubridate for dates, and ggplot2 for charts.

  • dplyr, one of those packages, supplies the verbs on the next slide
  • Every line of code today is tidyverse code, so the same lines work on any table you load

The Verbs of Data Wrangling

  • filter() keeps the rows that meet a condition
  • select() keeps or drops columns
  • mutate() adds a column or changes one, computed from other columns
  • arrange() reorders the rows by a column’s values
  • group_by() with summarize() collapses many rows into one row per group
  • Each verb takes a data frame (R’s name for a table) and returns a data frame, which is what lets the pipe chain them

Two Verbs, Seen

Pipe (%>%): read it as “and then”; it hands the result of one line to the next. Example: chat %>% filter(channel == "bobross") takes the chat table, then keeps Bob Ross’s messages.

chat %>%
  filter(channel == "bobross")

chat %>%
  select(channel, sender, message)
  • The first command keeps only Bob Ross’s messages and drops every other row
  • The second keeps three columns and drops the rest

Loading the Tables

chat <- twitch_chat()
streams <- twitch_streams()

posts <- read_csv("your-file.csv")
  • twitch_chat() and twitch_streams() load the two example tables from the v2v package
  • read_csv() from the tidyverse reads a CSV file into a table; that is how you load your own data
  • From here on, every step works the same on either

Transformation 1, a Readable Timestamp

chat <- chat %>%
  mutate(ts = as_datetime(date / 1000))

streams <- streams %>%
  mutate(ts = as_datetime(date / 1000))
  • Type or paste these lines into the worksheet’s Task 3.1 chunk, then run the chunk
  • as_datetime() comes from lubridate, the tidyverse package for dates; library(tidyverse) loads it
  • mutate() writes the result into a new ts column and leaves date as it was

Transformation 1, a Readable Timestamp (cont.)

  • date counts milliseconds since 1970, and R’s date-times count seconds, so the line divides date by 1,000 before as_datetime() turns it into a date and time
  • A column that counts milliseconds since 1970 is divided by 1,000; a column that counts seconds is not
  • Dates stored as text use ymd_hms() or ymd() instead
    • mutate(ts = ymd_hms(posted_at)) reads text such as 2024-03-01 14:05:00
    • mutate(day = ymd(posted_on)) reads text such as 2024-03-01
  • Exported data usually stores dates as text, so ymd_hms() is the line you will most often need

Dates Are Stored in Milliseconds

Timestamp: the date and time something happened. Example: 1542578127023 is the first message’s timestamp, 9:55 PM on November 18, 2018 (UTC).

  • date counts milliseconds since 1 January 1970
    • That starting moment is the Unix epoch
  • A date-time function such as as_datetime() expects seconds, which are a thousand times coarser
  • Hand it the raw number and every message is dated around the year 50,850
  • date / 1000 does that division, so as_datetime() receives seconds

The Column Type Changes to a Date-Time

# 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 type moved from <dbl>, a decimal number, to <dttm>, a date-time
  • Only from a date-time can you pull out the hour, the weekday, or the calendar date
  • Once converted, the timestamp is an interval variable (Chapter 8, Levels of measurement)

Opening Write R Code

The VS Code Command Palette at the top of the window. The search box reads AURA: Write R code, and the highlighted first result is the command AURA: Write R code.
  • Ctrl+Shift+P (Cmd+Shift+P on a Mac), type AURA: Write R code, then press Enter

Transformation 2, Message Length

  • Type the block, or let the R Companion write it: AURA: Write R code, then R2 Data, then Add a column (mutate), then select Run it
chat <- chat %>%
  mutate(message_length = str_length(message))

chat %>%
  select(message, message_length) %>%
  slice_head(n = 3)
  • str_length() counts the characters in a string, R’s name for a piece of text
  • mutate() writes the count into a new column
  • The example codebook names this variable (Chapter 8, A codebook for the chat study)

What the Lengths Look Like

# 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: it has a true zero and equal intervals, so it can be averaged
  • Eight, twenty-three, and 441 characters are all real Twitch chat messages
  • Week 12 describes the shape of that spread

Tidy Data, Defined

“Tidy data is a standard way of mapping the meaning of a dataset to its structure.”

Wickham (2014, p. 4)

  • Tidy data has one observation per row, one variable per column, and one value per cell
  • Tidiness is not a preference. It is the structural assumption every tidyverse function makes about its inputs and keeps in its outputs

Exercise: Meaning and Structure

Wickham (2014)

“Tidy data is a standard way of mapping the meaning of a dataset to its structure.”

Wickham (2014, p. 4)

  • In one sentence, what would one row of your own data mean (for example, “one comment on one post”)?
  • Where might your data’s structure not match that meaning, such as two values in one cell?
  • Is tidiness a property of the data, or of the question you ask of it? Give one reason

Joins, Defined

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 the game and viewers of its channel’s latest stream snapshot.

  • Steps 1 and 4 below are both joins
  • Step 4 matches rows on channel alone
  • Step 1 matches on channel and on time: the nearest snapshot at or before each message

Step 1, Match Each Message to Its Stream

snapshots <- streams %>%
  select(channel, ts, game, viewers) %>%
  rename(snapshot_ts = ts)

chat_streams <- chat %>%
  left_join(
    snapshots,
    by = join_by(channel, closest(ts >= snapshot_ts))
  )
  • The first block keeps the four stream columns the study needs and gives the snapshot time its own name
  • The second gives each message the game and viewers of the latest earlier snapshot on its channel
  • Both tables need ts from Transformation 1

Step 1, Checked

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)
  • The row count is still 35,267: a left join keeps every row of the left table

The Join, in Plain Language

  • join_by(channel, closest(ts >= snapshot_ts)) says: same channel, and of the snapshots at or before the message, the closest one
  • Each row is matched to the most recent earlier row with the same key: a rolling join
  • Use it whenever one table records events as they happen and the other records readings taken every so often
    • Posts matched to the follower count at the time; sales matched to the price in force
  • rename() gives the time column on one side its own name, because two columns both called ts would come back as ts.x and ts.y
  • More detail: Chapter 11, Matching each message to its stream

Step 2, Load the Channel Labels

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
  • twitch_channels() loads the example lookup table; your own lookup table is a second file read with read_csv()

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; your reviewer-facing comments 1 and 2 are about 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, the Join

  • Type the join, or let the R Companion write it: AURA: Write R code, then R2 Data, then Join two tables by a shared column
chat_streams <- chat_streams %>%
  left_join(channels, by = "channel")

Step 4, the Join (cont.)

  • channels is the lookup table: one row per channel, looked up by the join
  • left_join() keeps every row and attaches each channel’s five label columns, matching on the shared channel key
  • chat_streams already has a game column: the category streaming at that moment
    • main_game is the channel’s usual category, and later analyses use it

Joins Fail Silently When Keys Disagree

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 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 v2v example data has matching keys. Raw data does not
  • Check the key column in your own source before every join

Always Inspect a Derived Column

chat_streams %>%
  count(is_gaming)
# A tibble: 3 × 2
  is_gaming     n
  <lgl>     <int>
1 FALSE      3457
2 TRUE      31309
3 NA          501
  • Counting the new column takes one line
  • It catches problems you did not expect, such as the 501 NA values here

The NA Is the Correct Outcome

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
    • No category means no row in the lookup table, so the join left their messages as NA
  • The data does not say whether those 501 messages came from gaming channels
  • An honest NA records that the study cannot classify them
  • Those messages are left out of the comparison rather than guessed into one side

Two Columns the Join Brought In

  • viewer_band puts each channel in a band by its median viewers: small, medium, or large
  • channel_type writes is_gaming as words, “gaming” or “non-gaming”
  • Both are stored as a factor: R’s way of storing categories in an order you choose
    • Worksheet Tasks 4.3 and 4.4 count each one and read the order back
  • Weeks 12 and 13, and the R Companion’s chart and test blocks, group by these two columns

The Whole Pipeline, Three Tables

chat <- twitch_chat() %>%
  mutate(ts = as_datetime(date / 1000)) %>%
  mutate(message_length = str_length(message))

snapshots <- twitch_streams() %>%
  mutate(ts = as_datetime(date / 1000)) %>%
  select(channel, ts, game, viewers) %>%
  rename(snapshot_ts = ts)

channels <- twitch_channels()
  • Swap the three loaders for read_csv() lines and the same code runs on your own tables

The Whole Pipeline, Two Joins

analysis <- chat %>%
  left_join(
    snapshots,
    by = join_by(channel, closest(ts >= snapshot_ts))
  ) %>%
  left_join(channels, by = "channel")
  • Two transformations and two joins build the 15-column table
  • The worksheet adds your codes before it saves data/twitch_analysis.RDS, so save only from the worksheet

Saving the Table

  • In the worksheet’s Part 7, AURA: Write R code, then R2 Data, then Save a table as an RDS file writes the save line for the table analysis
  • write_rds() saves an RDS file, R’s own data file, with every column type intact

The Analysis-Ready Table

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 rows keep the chat table’s order, so the first ones are the earliest messages, sent before any snapshot: their three stream columns print NA

Your Script Is a Methods Section

  • The script is a documented chain of transformations, from raw data to analysis-ready data
    • Every mutate() and filter() is a methodological decision
    • Which cases to exclude, how to treat missing values, how to group time
  • A reviewer will ask how you handled something
    • The answer is in the script, if the script is commented and committed (saved to your GitHub history: Commit and Push With Git)

Three Decisions, Commented

  • Identify three decisions a reviewer could challenge
  • Write a comment on each, at the three places the worksheet marks
  • A comment the R Companion wrote does not count as one of your three
    • Write your own justification beside it

Never Overwrite Raw Data

  • Keep what you collected in data/raw/ exactly as it arrived; never edit it or save over it
    • Your script reads from it and writes new files, such as data/twitch_analysis.RDS, never back into it
  • That separation lets you rebuild everything from unchanged raw data
    • Overwriting the raw data breaks that guarantee, and it cannot be undone
  • Test it: render the worksheet with Quarto: Preview (Render a Quarto Document), which runs every chunk from the top in a fresh R session
  • If the script does not reproduce the table without your help, it depends on something it does not write down

Common Errors and What They Mean

  • Timestamps around the year 50,850: you converted by hand and forgot / 1000
  • could not find function "%>%" or "as_datetime": the tidyverse never loaded
  • Every joined column is ts.x and ts.y: the time column was not renamed before the join
  • Every joined column is NA: the keys disagree, often because of a #
  • The row count grew after a join: the lookup table has duplicate keys
  • object 'channels' not found: the gray boxes of code (chunks) ran out of order; run them from the top
  • could not find function "twitch_channels": your v2v is older than 0.3.8: run AURA: Check my setup, then Install what is missing

Explain an Error

  • Select the red error text in the terminal and press Ctrl+C (Cmd+C on a Mac) to copy it
  • Press Ctrl+Shift+P (Cmd+Shift+P) to open the Command Palette, the search box at the top of VS Code
  • Type AURA: Explain an R error and press Enter
  • The error you copied is already filled in; press Enter and the plain-English fix appears
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:

  • An analysis table with 15 columns and 35,267 rows
  • The worksheet adds your thirty codes, then saves data/twitch_analysis.RDS
  • A ts column of type <dttm> and a message_length column of type <int> (whole numbers)
  • An is_gaming column with 3,457 FALSE, 31,309 TRUE, and 501 NA
  • A commented worksheet that renders with no error (guide 11)
  • The processed dataset written out, with the raw data untouched

Before Week 12

Before Week 12 (cont.)

Questions, Comments, or Concerns?