Recoding Variables

Model script

#install.packages("tidyverse")  # uncomment if tidyverse not installed
#install.packages("rio")  # uncomment if rio not installed
library(tidyverse)
library(rio)

data <- import("https://learndata.net/nycschools.dta")

# we learned in the prior section one way to create binary indicators;
# we can also create a binary indicator using mutate() and case_when()
# this approach is more complicated but is flexible and works for
# many recoding tasks
data <- data |>
  mutate(grade_A = case_when(
    overallgrade == "A" ~ 1,
    overallgrade == "" ~ NA,
    .default  = 0
    )
  )

# create a table to check mapping of new variable to old one
table(data$overallgrade, data$grade_A, useNA = "ifany")

Key concepts/syntax:

  1. case_when(): a powerful but somewhat complex tidyverse function for recoding variables1

  1. For more explanation, see https://moderndive.com/v2/93-appendixC.html#sec-appendix-changing-values or https://r4ds.hadley.nz/logicals.html#case_when↩︎