R
Beginner
2 min read
ANOVA, Logistic Regression, and Model Evaluation
Example
# One-way ANOVA
data(PlantGrowth) # weight of plants under 3 conditions
aov_model <- aov(weight ~ group, data = PlantGrowth)
summary(aov_model)
# Post-hoc: Tukey HSD
TukeyHSD(aov_model)
# Two-way ANOVA
data(ToothGrowth)
aov2 <- aov(len ~ supp * dose, data = ToothGrowth)
summary(aov2)
# Logistic regression
# Create a binary outcome
data(mtcars)
mtcars$am <- factor(mtcars$am, labels = c("automatic", "manual"))
log_model <- glm(am ~ mpg + wt + hp,
data = mtcars,
family = binomial)
summary(log_model)
# Coefficients as odds ratios
exp(coef(log_model))
exp(confint(log_model))
# Fitted probabilities
fitted_probs <- predict(log_model, type = "response")
predicted_class <- ifelse(fitted_probs > 0.5, "manual", "automatic")
# Confusion matrix (manual)
table(Predicted = predicted_class, Actual = mtcars$am)
# Accuracy
mean(predicted_class == as.character(mtcars$am))
# Likelihood ratio test (compare to null model)
null_model <- glm(am ~ 1, data = mtcars, family = binomial)
anova(null_model, log_model, test = "LRT")
# Pseudo R-squared (McFadden)
1 - log_model$deviance / null_model$deviance