state_clean <-tolower(trimws(dat$`State They Are From`))age_raw <-trimws(dat$Age_Group)# Check: warn if any age labels won't match the factor levels belowage_levels <-c("18-19", "20-21", "22 and older")bad_ages <-unique(age_raw[!is.na(age_raw) &!(age_raw %in% age_levels)])if (length(bad_ages) >0) {warning("Unmatched Age_Group values (will become NA): ", paste(bad_ages, collapse =", "))}dat <- dat %>%mutate(# People who quit before the definition question are coded missing rather than 0.# To count them as 0 instead, change NA_real_ below to 0.Score =if_else(toupper(trimws(Defintion)) =="DID NOT ANSWER",NA_real_,as.numeric(`Final Score`) ),State =case_when( state_clean %in%c("mn", "minnesota", "minnestoa") ~"Minnesota", state_clean %in%c("wi", "wisconsin", "wisconson", "rice lake, wi") ~"Wisconsin", state_clean =="iowa"~"Iowa" ),Age_Group =factor(age_raw, levels = age_levels),State =factor(State, levels =c("Minnesota", "Wisconsin", "Iowa")) ) %>%filter(!is.na(State)) # Keep only Minnesota, Wisconsin, and Iowa# How many people in this data did not answer the definition questionn_no_answer <-sum(toupper(trimws(dat$Defintion)) =="DID NOT ANSWER", na.rm =TRUE)cat("Did not answer the definition question:", n_no_answer, "\n")
Did not answer the definition question: 63
# Counts and percentages for one variablefreq_table <-function(x) { counts <-table(x, useNA ="ifany")data.frame(Group =ifelse(is.na(names(counts)), "Missing", names(counts)),N =as.vector(counts),Percent =round(100*as.vector(counts) /sum(counts), 1) )}# Mean, SD, N, and one-way ANOVA p-valuecompare_score <-function(data, group) { d <- data %>%filter(!is.na(Score), !is.na(.data[[group]])) d$Group <-droplevels(factor(d[[group]])) p <-anova(lm(Score ~ Group, data = d))$`Pr(>F)`[1] d %>%group_by(Group) %>%summarise(Mean =round(mean(Score), 2), SD =round(sd(Score), 2), N =n(), .groups ="drop") %>%mutate(Pval =c(format.pval(p, digits =3, eps =0.001), rep("", n() -1)))}# 1. College distributionkable(arrange(freq_table(dat$College), desc(N)), caption ="College Distribution")