Transforming 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")

# convert quantitative variables currently
# stored as characters to numbers
data <- data |> mutate(iep = parse_number(iep))
data <- data |> mutate(blackhispanic = parse_number(blackhispanic))
data <- data |> mutate(ell = parse_number(ell))
data <- data |> mutate(thgrmathela = parse_number(thgrmathela))

# rename thgrmathela to something more descriptive
data <- data |> rename(combined_score = thgrmathela)

# log transform the ell variable
data <- data |> mutate(log_ell = log(ell))

# relocate new variable to be next to the original
data <- data |> relocate(log_ell, .after = ell)

# standard ell manually based on summary statistics
#install.packages("psych")  # uncomment if psych not installed
library(psych)
describe(data$ell)
data <- data |> mutate(z_ell = (ell - 13.79) / 12.33)

# drop the standardized variable and then recreate
# it with simpler automated syntax, using scale()
data <- data |> select(!z_ell)
data <- data |> mutate(z_ell = scale(ell))
data <- data |> relocate(z_ell, .after = ell)

Key concepts/syntax:

  1. |>: this is called a “pipe” (sometimes also written as %>%), here we use it to connect our dataset (data) to a data manipulation function (e.g., mutate(), rename())1

    data <- data |> mutate(iep = parse_number(iep))
  2. mutate(): create a new variable (or overwrite an existing one), using the dplyr package which can be loaded in with library(tidyverse)2

    data <- data |> mutate(z_ell = (ell - 13.79) / 12.33)
  3. parse_number(): convert a character variable to a numeric one by ignoring all non-numeric characters3

    data <- data |> mutate(iep = parse_number(iep))
  4. rename(): rename a variable, using the dplyr package

    data <- data |> rename(combined_score = thgrmathela)
  5. log(): a function to create a log transformation (based on the natural log)

    data <- data |> mutate(log_ell = log(ell))
  6. relocate(): rearrange the ordering of variables, using the dplyr package

    data <- data |> relocate(log_ell, .after = ell)
  7. select(): select only a subset of variables (e.g., all but z_ell), using the dplyr package

    data <- data |> select(!z_ell)
  8. !: means “not” (e.g., as is “not this variable”)

    data <- data |> select(!z_ell)
  9. scale(): standardize a set of values (e.g., from a variable)

    data <- data |> mutate(z_ell = scale(ell))

  1. For a more complete explanation, see https://moderndive.com/v2/03-wrangling.html#sec-piping or https://r4ds.hadley.nz/data-transform.html#sec-the-pipe↩︎

  2. For more explanation of this and most other functions used in this section, see https://r4ds.hadley.nz/data-transform.html#columns↩︎

  3. For more explanation, see https://r4ds.hadley.nz/numbers.html#making-numbers↩︎