| 1 |
#' @templateVar class mlm |
| 2 |
#' @template title_desc_tidy |
| 3 |
#' |
| 4 |
#' @param x An `mlm` object created by [stats::lm()] with a matrix as the |
| 5 |
#' response. |
| 6 |
#' @template param_confint |
| 7 |
#' @template param_unused_dots |
| 8 |
#' |
| 9 |
#' @evalRd return_tidy(regression = TRUE) |
| 10 |
#' |
| 11 |
#' @details In contrast to `lm` object (simple linear model), tidy output for |
| 12 |
#' `mlm` (multiple linear model) objects contain an additional column |
| 13 |
#' `response`. |
| 14 |
#' |
| 15 |
#' If you have missing values in your model data, you may need to refit |
| 16 |
#' the model with `na.action = na.exclude`. |
| 17 |
#' |
| 18 |
#' @examples |
| 19 |
#' |
| 20 |
#' # fit model |
| 21 |
#' mod <- lm(cbind(mpg, disp) ~ wt, mtcars) |
| 22 |
#' |
| 23 |
#' # summarize model fit with tidiers |
| 24 |
#' tidy(mod, conf.int = TRUE) |
| 25 |
#' |
| 26 |
#' @export |
| 27 |
#' @seealso [tidy()] |
| 28 |
#' @family lm tidiers |
| 29 |
#' @export |
| 30 |
tidy.mlm <- function(x, conf.int = FALSE, conf.level = 0.95, ...) { |
| 31 |
check_ellipses("exponentiate", "tidy", "mlm", ...) |
| 32 |
|
| 33 |
# adding other details from summary object |
| 34 |
s <- summary(x) |
| 35 |
|
| 36 |
co <- stats::coef(s) |
| 37 |
nn <- c("estimate", "std.error", "statistic", "p.value") |
| 38 |
|
| 39 |
# multiple response variables |
| 40 |
ret <- map_as_tidy_tibble( |
| 41 |
co, |
| 42 |
new_names = nn[1:ncol(co[[1]])], |
| 43 |
id_column = "response" |
| 44 |
) |
| 45 |
|
| 46 |
ret$response <- stringr::str_replace(ret$response, "Response ", "") |
| 47 |
|
| 48 |
ret <- as_tibble(ret) |
| 49 |
|
| 50 |
if (conf.int) { |
| 51 |
# S3 method for computing confidence intervals for `mlm` objects was |
| 52 |
# introduced in R 3.5 |
| 53 |
CI <- tryCatch( |
| 54 |
stats::confint(x, level = conf.level), |
| 55 |
error = function(x) { |
| 56 |
NULL |
| 57 |
} |
| 58 |
) |
| 59 |
|
| 60 |
# if R version is prior to 3.5, use the custom function |
| 61 |
if (is.null(CI)) { |
| 62 |
CI <- confint_mlm(x, level = conf.level) |
| 63 |
} |
| 64 |
|
| 65 |
colnames(CI) <- c("conf.low", "conf.high") |
| 66 |
ret <- dplyr::bind_cols(ret, as_tibble(CI)) |
| 67 |
} |
| 68 |
|
| 69 |
as_tibble(ret) |
| 70 |
} |
| 71 |
|
| 72 |
# compute confidence intervals for mlm object. |
| 73 |
confint_mlm <- function(object, level = 0.95, ...) { |
| 74 |
coef <- as.numeric(coef(object)) |
| 75 |
alpha <- (1 - level) / 2 |
| 76 |
crit_val <- qt(c(alpha, 1 - alpha), object$df.residual) |
| 77 |
se <- sqrt(diag(stats::vcov(object))) |
| 78 |
ci <- as.data.frame(coef + se %o% crit_val) |
| 79 |
colnames(ci) <- c("conf.low", "conf.high") |
| 80 |
ci |
| 81 |
} |