Wrangling the Data

S21 · Chapter 11

Today’s Agenda

  • The Twitch job: three worksheets, one study
  • Why the table you loaded cannot answer your research question yet
  • The five dplyr verbs that reshape a table
  • Converting timestamps into readable dates, and the factor of a thousand that breaks the conversion
  • Message length: the first variable you compute from the data

From Raw Data to Analysis-Ready Data

  • The example chat table cannot answer the example question yet
  • Today: five verbs, then two transformations
    • Readable timestamps, and message length
    • Thursday adds the gaming label and joins the two tables
  • Today’s steps produce no results yet, but every later result depends on them
  • Wrangling is slow, repetitive work, and professionals 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
    • Under each step: what you should see
  • Part 0: hand-code thirty messages as reaction or commentary
    • Inferencing tests the variable you build here
  • Each worksheet has a risks guide: the traps, and how to check for them

Data Wrangling worksheet · Data Wrangling risks guide

What the Table Cannot Answer

  • The example study compares gaming and non-gaming chat
    • 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
  • Whether a channel was gaming sits in the other table, which is not yet linked
  • Your own data will probably lack some columns your question needs; the same steps 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 rarely described in the published paper, and it is most of the work
    • Each step is small and technical
    • Together, the steps build the table every result depends on

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 and a chart theme.

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 and ggplot2 for charts.

  • dplyr, one of those packages, supplies today’s five verbs

The Verbs: filter() and select()

chat %>%
  filter(channel == "bobross")
  • filter() keeps the rows that meet a condition and drops the rest
    • Here it keeps only Bob Ross’s messages
chat %>%
  select(channel, sender, message)
  • select() keeps or drops columns
    • Here it narrows five columns to three

The Verbs: mutate(), arrange(), group_by(), and summarize()

  • 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
    • That pair is how you get one number per channel, such as its message count

Chapter 11 uses these five verbs for most of its wrangling (The verbs of data wrangling).

Why the Verbs Chain Together

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.

  • Each verb takes a data frame (R’s name for a table) and returns a data frame
    • That shared design is what lets %>% string them together
    • One verb’s output is the next verb’s input
  • A pipeline reads in order: take the data, then do this, then do that
  • Today and Thursday, four transformations built this way turn the example chat table into the table the study needs

Exercise: Work Out the Output Before You Run It

chat %>%
  filter(channel == "bobross") %>%
  select(sender, message)

Work out your answers before running the code.

  • How many columns come back? How many rows?
  • What changes in the result if the filter() line and the select() line swap places?
  • What happens if you type channel = "bobross" with one equals sign instead of two?

The Unreadable Timestamp

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

  • date is a column of very large numbers, typed <dbl> (a column of decimal numbers)
    • Each number counts milliseconds since midnight on 1 January 1970
  • That starting moment is called the Unix epoch
    • Counting from it stores a whole timestamp as one number
    • The number is exact, but no person can read it as a date
  • Once converted, the timestamp is an interval variable (Chapter 8, Levels of measurement)

Converting the Timestamp

  • Type this block into the worksheet’s Task 3.1 chunk, then run it
chat <- chat %>%
  mutate(ts = as_datetime(date / 1000))
streams <- streams %>%
  mutate(ts = as_datetime(date / 1000))
  • as_datetime() turns a count of seconds into a date and time
    • It comes from lubridate, the tidyverse package for dates, which library(tidyverse) loads
  • date / 1000 turns milliseconds into seconds first
  • mutate() stores the result in a new column, ts

Converting the Timestamp (cont.)

  • The same verb handles the dates your own data carries
    • A count of seconds: as_datetime(column)
    • Text such as 2024-03-01 14:22:05: ymd_hms(column)
    • Text such as 3/1/2024: mdy(column)
  • lubridate names each reader after the order the text writes year, month, and day
  • Run ?ymd_hms to see the whole family

The Factor of a Thousand That Breaks It

  • as_datetime() expects seconds
    • date counts milliseconds, which is a thousand times finer
  • Hand it the raw number and every message is dated around the year 50,850
  • date / 1000 converts milliseconds to seconds first
  • Writing the division yourself is the habit to keep: every timestamp you meet later needs you to know its unit

A missing / 1000 is the mistake to check for whenever you convert a timestamp.

Seeing the Conversion

chat %>%
  select(date, ts) %>%
  slice_head(n = 3)
           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 moments are now readable: three messages eight seconds apart
  • The type changed from <dbl> to <dttm>, a date-time
    • A date-time gives you the hour and the weekday, which the raw number does not

Measuring Message Length

  • Type this block into Task 3.2, or let the R Companion write it: AURA: Write R code, then R2 Data, then Add a column (mutate)
chat <- chat %>%
  mutate(message_length = str_length(message))
  • str_length() counts the characters in a string, R’s name for a piece of text
  • mutate() stores that count as a new column
  • The example codebook names this variable (Chapter 8, A codebook for the chat study)
    • The data did not contain it until now

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

What the Lengths Show

chat %>%
  select(message, message_length) %>%
  slice_head(n = 3)
  message                          message_length
1 "???????????????????????"                    23
2 "TriEasy Clap TriEasy Clap…"                441
3 "cmonBruh"                                    8
  • One emote name is 8 characters, the row of question marks is 23, and a block of repeated pasted text is 441
  • message_length is a ratio variable: it has a true zero and equal intervals, so it is safe to average

Common Errors Today

  • Every message is dated around the year 50,850: you converted by hand and forgot / 1000
  • could not find function "str_length": you have not run library(tidyverse)
  • object 'message_length' not found: R has nothing by that name yet (R calls anything you have named an object): you never assigned the result back to chat
    • <- is what makes a change stick
  • unexpected '=': usually a single = where == belongs

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 chat object and a streams object, each with a working ts column, typed <dttm>
  • A message_length column on chat, typed <int> (whole numbers)
  • Output showing dates in November 2018
  • Today’s steps filled in your worksheet, not typed into the console (the R terminal, where typed lines are not saved)
  • Any step the R Companion wrote (AURA: Write R code, R2 Data) sits in the worksheet with its comments

Still missing: the gaming label. That is Thursday.

Coding in the Data Viewer

The R Companion data viewer titled coding-form (30 rows), with the buttons Refresh, Add coding column, Hide pass 1, Insert rebuild code, and Write this view as R. The line under the buttons reads reaction_only, row 1: 1. Saved, with the time and 1 coded cell(s). A new reaction_only column holds 1 in row 1, and the empty cell in row 2 is selected.
  • AURA: Open the data viewer on data/coding-form.csv, then Add coding column
  • Type each code in the new column; the line under the buttons confirms each save

Before Thursday

Before Thursday (cont.)

  • Due Friday, November 6, 11:59 PM: Sampling Plan and Pilot, 75 points
  • Due Friday, November 13, 11:59 PM: Data Wrangling in R, 50 points
  • Thursday: the gaming label, the join, and the rows a join leaves behind
  • Bring your worksheet, because Thursday picks it up where it stops
  • Check yourself on this week’s terms: Week 11 self-check, ungraded, with the answer after each question

Questions, Comments, or Concerns?