
The MSE, defined as the sum of the squared residuals divided by n-p
(n
= number of observations, p
= number of regression
coefficients), is an unbiased estimator for the error variance in a linear
regression model. This is a convenience function that extracts the MSE from
a fitted lm
or glm
object. The code is
rev(anova(model.fit)$"Mean Sq")[1]
if model.fit
is a
lm
object and
sum(model.fit$residuals^2) / model.fit$df.residual
if model.fit
is a glm
object.
get_mse(model.fit, var.estimate = FALSE)
If TRUE
, function returns a variance estimate for
the error variance, defined as 2 * MSE^2 / (n - p)
.
If var.estimate = FALSE
, numeric value indicating the MSE; if
var.estimate = TRUE
, named numeric vector indicating both the MSE and
a variance estimate for the error variance.
# NOT RUN {
# Generate 100 values: Y = 0.5 + 1.25 X + e, e ~ N(0, 1)
set.seed(123)
x <- rnorm(100)
y <- 0.5 + 1.25 * x + rnorm(100, sd = 1)
# Fit regression model using lm and using glm
lm.fit <- lm(y ~ x)
glm.fit <- glm(y ~ x)
# Extract MSE from lm.fit and glm.fit
get_mse(lm.fit)
get_mse(glm.fit)
# }
Run the code above in your browser using DataLab