Debian Codegraph @

tests/testthat/test-boot.R

raw
1 skip_on_cran()
2
3 skip_if_not_installed("modeltests")
4 library(modeltests)
5
6 skip_if_not_installed("boot")
7 suppressPackageStartupMessages(library(boot))
8
9 test_that("boot tidier arguments", {
10 check_arguments(tidy.boot)
11 })
12
13 test_that("tidy.boot for glms", {
14 clotting <- data.frame(
15 u = c(5, 10, 15, 20, 30, 40, 60, 80, 100),
16 lot1 = c(118, 58, 42, 35, 27, 25, 21, 19, 18),
17 lot2 = c(69, 35, 26, 21, 18, 16, 13, 12, 12)
18 )
19
20 g1 <- glm(lot2 ~ log(u), data = clotting, family = Gamma)
21
22 boot_fun <- function(d, i) {
23 stats::coef(stats::update(g1, data = d[i, ]))
24 }
25
26 bootres <- boot::boot(clotting, boot_fun, R = 100)
27 td <- tidy(bootres, conf.int = TRUE)
28
29 tdnorm <- tidy(bootres, conf.int = TRUE, conf.method = "norm")
30 expect_false(any(is.na(tdnorm[[4]])))
31
32 bootresw <- boot::boot(clotting, boot_fun, R = 100, weights = rep(1 / 9, 9))
33 tdw <- tidy(bootresw, conf.int = TRUE)
34 tdwe <- tidy(bootresw, conf.int = TRUE, exponentiate = TRUE)
35
36 check_tidy_output(td)
37 check_tidy_output(tdw)
38 check_tidy_output(tdwe)
39
40 check_dims(td, 2, 6)
41 check_dims(tdw, 2, 7)
42 check_dims(tdwe, 2, 7)
43
44 expect_equal(exp(tdw$statistic), tdwe$statistic)
45 expect_equal(exp(tdw$conf.low), tdwe$conf.low)
46 })
47
48 test_that("tidy.boot for time series", {
49 lynx.fun <- function(tsb) {
50 ar.fit <- ar(tsb, order.max = 25)
51 c(ar.fit$order, mean(tsb), tsb)
52 }
53
54 lynx <- boot::tsboot(log(lynx), lynx.fun, R = 99, l = 20, orig.t = FALSE)
55 td <- tidy(lynx)
56
57 check_tidy_output(td)
58 check_dims(td, expected_cols = 2)
59 })
60
61 test_that("dimensionality of CIs is correct (#1212)", {
62 set.seed(123)
63 d = data.frame(v1 = rnorm(100), v2 = rnorm(100))
64 boot1 <- function(d, i) {
65 d = d[i, ]
66 c(mean(d$v1), mean(d$v2), cor(d$v1, d$v2))
67 }
68 boot2 <- function(d, i) {
69 d = d[i, ]
70 c(mean(d$v1), mean(d$v2))
71 }
72 boot3 <- function(d, i) {
73 d = d[i, ]
74 c(mean(d$v1))
75 }
76
77 r1 <- boot(d, boot1, 100)
78 r2 <- boot(d, boot2, 100)
79 r3 <- boot(d, boot3, 100)
80
81 td1 <- tidy(r1, conf.int = T, conf.method = "norm")
82 td2 <- tidy(r2, conf.int = T, conf.method = "norm")
83 td3 <- tidy(r3, conf.int = T, conf.method = "norm")
84
85 check_tidy_output(td1)
86 check_tidy_output(td2)
87 check_tidy_output(td3)
88 })