| 1 |
skip_if_not_installed("modeltests") |
| 2 |
library(modeltests) |
| 3 |
|
| 4 |
pc <- prcomp(USArrests, scale = TRUE) |
| 5 |
|
| 6 |
test_that("prcomp tidier arguments", { |
| 7 |
check_arguments(tidy.prcomp) |
| 8 |
check_arguments(augment.prcomp, strict = FALSE) |
| 9 |
}) |
| 10 |
|
| 11 |
|
| 12 |
test_that("tidy.prcomp", { |
| 13 |
td <- tidy(pc, matrix = "d") |
| 14 |
|
| 15 |
check_tidy_output(td) |
| 16 |
check_dims(td, 4, 4) |
| 17 |
expect_identical(tidy(pc, matrix = "pcs"), td) |
| 18 |
expect_identical(tidy(pc, matrix = "eigenvalues"), td) |
| 19 |
|
| 20 |
td2 <- tidy(pc, matrix = "v") |
| 21 |
|
| 22 |
check_tidy_output(td2, strict = FALSE) |
| 23 |
check_dims(td2, 16, 3) |
| 24 |
|
| 25 |
expect_identical( |
| 26 |
tidy(pc, matrix = "rotation"), |
| 27 |
tidy(pc, matrix = "variables") |
| 28 |
) |
| 29 |
expect_identical(tidy(pc, matrix = "rotation"), td2) |
| 30 |
expect_identical(tidy(pc, matrix = "variables"), td2) |
| 31 |
expect_identical(tidy(pc, matrix = "loadings"), td2) |
| 32 |
|
| 33 |
td3 <- tidy(pc, matrix = "u") |
| 34 |
|
| 35 |
check_tidy_output(td3) |
| 36 |
check_dims(td3, 200, 3) |
| 37 |
expect_identical(tidy(pc, matrix = "x"), tidy(pc, matrix = "samples")) |
| 38 |
expect_identical(tidy(pc, matrix = "x"), td3) |
| 39 |
expect_identical(tidy(pc, matrix = "samples"), td3) |
| 40 |
expect_identical(tidy(pc, matrix = "scores"), td3) |
| 41 |
|
| 42 |
expect_snapshot(error = TRUE, tidy(pc, matrix = c("d", "u"))) |
| 43 |
|
| 44 |
no_row_nm <- as.data.frame(matrix(1:9, ncol = 3) + rnorm(n = 9, sd = 0.25)) |
| 45 |
pca <- prcomp(no_row_nm) |
| 46 |
expect_no_error(tidy(pca, matrix = "u")) |
| 47 |
}) |
| 48 |
|
| 49 |
test_that("augment.prcomp", { |
| 50 |
check_augment_function( |
| 51 |
aug = augment.prcomp, |
| 52 |
model = pc, |
| 53 |
data = USArrests, |
| 54 |
newdata = USArrests, |
| 55 |
strict = FALSE |
| 56 |
) |
| 57 |
}) |
| 58 |
|
| 59 |
test_that("augment.prcomp works with matrix objects", { |
| 60 |
suppressPackageStartupMessages(library(broom)) |
| 61 |
set.seed(17) |
| 62 |
|
| 63 |
# data |
| 64 |
C <- chol(S <- toeplitz(.9^(0:31))) |
| 65 |
X <- matrix(rnorm(32000), 1000, 32) |
| 66 |
Z <- X %*% C |
| 67 |
|
| 68 |
# model |
| 69 |
pZ <- stats::prcomp(Z, tol = 0.1) |
| 70 |
|
| 71 |
# using stats predict method |
| 72 |
pred <- as.data.frame(predict(pZ)) |
| 73 |
names(pred) <- paste0(".fitted", names(pred)) |
| 74 |
|
| 75 |
# with data |
| 76 |
df1 <- broom::augment(pZ) |
| 77 |
|
| 78 |
# without data |
| 79 |
df2 <- broom::augment(pZ, data = Z) |
| 80 |
|
| 81 |
expect_equal(dim(df1), c(1000L, 15L)) |
| 82 |
expect_equal(dim(df2), c(1000L, 47L)) |
| 83 |
testthat::expect_equal(tibble::as_tibble(pred), df1[, -1]) |
| 84 |
expect_s3_class(df1, "tbl_df") |
| 85 |
}) |