| 1 |
skip_on_cran() |
| 2 |
|
| 3 |
skip_if_not_installed("modeltests") |
| 4 |
library(modeltests) |
| 5 |
|
| 6 |
fit_mlm <- lm(cbind(mpg, disp) ~ wt, mtcars) |
| 7 |
df_tidy <- tidy(fit_mlm, conf.int = TRUE) |
| 8 |
|
| 9 |
test_that("tidy.mlm works", { |
| 10 |
expect_equal(dim(df_tidy), c(4L, 8L)) |
| 11 |
expect_s3_class(df_tidy, "tbl_df") |
| 12 |
}) |
| 13 |
|
| 14 |
#' helper function: replicate each element of x |
| 15 |
#' times times. |
| 16 |
rep_each <- function(x, times) { |
| 17 |
retv <- outer(rep(1, times), x, function(x, y) y) |
| 18 |
dim(retv) <- c(prod(dim(retv)), 1) |
| 19 |
retv <- switch( |
| 20 |
class(x), |
| 21 |
character = as.character(retv), |
| 22 |
numeric = as.numeric(retv), |
| 23 |
integer = as.integer(retv), |
| 24 |
retv |
| 25 |
) |
| 26 |
retv |
| 27 |
} |
| 28 |
|
| 29 |
test_that("tidy.mlm works", { |
| 30 |
# create data |
| 31 |
nob <- 100 |
| 32 |
set.seed(1234) |
| 33 |
datf <- |
| 34 |
data.frame( |
| 35 |
x1 = rnorm(nob), |
| 36 |
x2 = runif(nob), |
| 37 |
z1 = rnorm(nob), |
| 38 |
z2 = rnorm(nob) |
| 39 |
) |> |
| 40 |
dplyr::mutate( |
| 41 |
y1 = 0.5 * x1 + x2 + z1 - z2, |
| 42 |
y2 = -2 * x1 + 0.25 * x2 + 3 * z1 + z2 |
| 43 |
) |
| 44 |
|
| 45 |
# fit two mlm objects |
| 46 |
fit <- lm(cbind(y1, y2) ~ x1, data = datf) |
| 47 |
fit2 <- lm(cbind(y1, y2) ~ x1 + x2, data = datf) |
| 48 |
|
| 49 |
# tidy dataframe |
| 50 |
td <- tidy(fit) |
| 51 |
td2 <- tidy(fit2) |
| 52 |
|
| 53 |
# hit the confidence interval code |
| 54 |
tdc <- tidy(fit, conf.int = TRUE) |
| 55 |
tdc2 <- tidy(fit2, conf.int = TRUE) |
| 56 |
|
| 57 |
modeltests::check_tidy_output(td) |
| 58 |
modeltests::check_tidy_output(td2) |
| 59 |
modeltests::check_tidy_output(tdc) |
| 60 |
modeltests::check_tidy_output(tdc2) |
| 61 |
|
| 62 |
modeltests::check_dims(td, expected_rows = 4) |
| 63 |
modeltests::check_dims(td2, expected_rows = 6) |
| 64 |
modeltests::check_dims(tdc, expected_rows = 4) |
| 65 |
modeltests::check_dims(tdc2, expected_rows = 6) |
| 66 |
|
| 67 |
modeltests::check_dims(td, expected_cols = 6) |
| 68 |
modeltests::check_dims(td2, expected_cols = 6) |
| 69 |
modeltests::check_dims(tdc, expected_cols = 8) |
| 70 |
modeltests::check_dims(tdc2, expected_cols = 8) |
| 71 |
|
| 72 |
expect_equal(td$term, rep(c("(Intercept)", "x1"), 2)) |
| 73 |
expect_equal(td2$term, rep(c("(Intercept)", "x1", "x2"), 2)) |
| 74 |
expect_equal(td$response, rep_each(c("y1", "y2"), 2)) |
| 75 |
expect_equal(td2$response, rep_each(c("y1", "y2"), 3)) |
| 76 |
}) |