Data Management
Model script
#install.packages("tidyverse") # uncomment if tidyverse not installed
#install.packages("rio") # uncomment if rio not installed
#install.packages("fastDummies") # uncomment if fastDummies not installed
library(tidyverse)
library(rio)
library(fastDummies)
data <- import("https://learndata.net/nycschools.dta")
# create a factor variable from a string variable
data <- data |>
mutate(grade_factor = factor(overallgrade, exclude = ""))
# create a table to check mapping of new variable to old one
table(data$overallgrade, data$grade_factor, useNA = "ifany")
# create dummy variables from the original string variable
data <- data |>
dummy_cols("overallgrade")
# create a table to check how the coding of the first new
# dummy variable compares to the original variable,
# with NAs included in the table (to check how missing
# data is handled)
table(data$overallgrade, data$overallgrade_A, useNA = "ifany")
# since NAs were handled incorrectly, drop these dummy
# variables from the dataset and start over
data <- data |>
select(!overallgrade_:overallgrade_F)
# let's instead try feeding the factor variable we created into
# the dummy_cols function (so NAs are handled correctly)
data <- data |>
dummy_cols("grade_factor")
# we again create a table to double-check what the coding looks
# like for one of our new dummy variables
table(data$overallgrade, data$grade_factor_A, useNA = "ifany")
# we can also check how the dummy variable indicating missingness
# is coded:
table(data$overallgrade, data$grade_factor_NA, useNA = "ifany")Key concepts/commands:
No new functions were introduced in this lesson. But whenever manipulating variables, remember to double-check whether you’ve correctly handled missing values (NA for numeric/factor variables; "" for string variables). The useNA parameter of the table() function often helps with investigating this.