## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment  = "#>"
)
library(AMCP)

## -----------------------------------------------------------------------------
data(chapter_9_exercise_15)
pyg <- chapter_9_exercise_15            # work on a copy
table(pyg$Treatment)                    # 246 control, 64 "bloomer"

pyg$group <- factor(pyg$Treatment,
                    levels = c(0, 1),
                    labels = c("Control", "Bloomer"))
table(pyg$group)

## -----------------------------------------------------------------------------
f_numeric <- anova(lm(IQGain ~ Treatment, data = pyg))
f_factor  <- anova(lm(IQGain ~ group,     data = pyg))

c(F_numeric = f_numeric[["F value"]][1],
  F_factor  = f_factor[["F value"]][1])

## -----------------------------------------------------------------------------
data(chapter_4_table_1)
d4 <- chapter_4_table_1
sort(unique(d4$cond))

# WRONG for a grouping variable: 'cond' enters as one numeric slope
# (1 numerator df), testing only a linear trend across the codes.
anova(lm(bloodpr ~ cond, data = d4))

# RIGHT: factor(cond) enters as four groups (3 numerator df), the
# one-way ANOVA the book intends.
anova(lm(bloodpr ~ factor(cond), data = d4))

## -----------------------------------------------------------------------------
likely_factors <- function(df) {
  looks_categorical <- function(x) {
    if (!is.numeric(x)) return(FALSE)
    u <- unique(x[!is.na(x)])
    length(u) <= 6 && all(u == floor(u))
  }
  names(df)[vapply(df, looks_categorical, logical(1))]
}

likely_factors(chapter_7_table_16)   # e.g., Sex, Education
likely_factors(chapter_16_table_1)   # e.g., Trainee, Gender

