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:
|>: 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())1data <- data |> mutate(iep = parse_number(iep))mutate(): create a new variable (or overwrite an existing one), using thedplyrpackage which can be loaded in withlibrary(tidyverse)2data <- data |> mutate(z_ell = (ell - 13.79) / 12.33)parse_number(): convert a character variable to a numeric one by ignoring all non-numeric characters3data <- data |> mutate(iep = parse_number(iep))rename(): rename a variable, using thedplyrpackagedata <- data |> rename(combined_score = thgrmathela)log(): a function to create a log transformation (based on the natural log)data <- data |> mutate(log_ell = log(ell))relocate(): rearrange the ordering of variables, using thedplyrpackagedata <- data |> relocate(log_ell, .after = ell)select(): select only a subset of variables (e.g., all butz_ell), using thedplyrpackagedata <- data |> select(!z_ell)!: means “not” (e.g., as is “not this variable”)data <- data |> select(!z_ell)scale(): standardize a set of values (e.g., from a variable)data <- data |> mutate(z_ell = scale(ell))
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↩︎
For more explanation of this and most other functions used in this section, see https://r4ds.hadley.nz/data-transform.html#columns↩︎
For more explanation, see https://r4ds.hadley.nz/numbers.html#making-numbers↩︎