Debian Codegraph @

tests/testthat/test_intercept_formulas.R

raw
1 context("population mean estimation")
2 set.seed(20190513)
3
4 m <- 14
5 icc <- 0.2
6 mu <- 5
7 size <- 2
8 nj <- 1 + rnbinom(m, size = size, mu = mu)
9 group <- factor(rep(LETTERS[1:m], nj))
10 N <- sum(nj)
11
12 Y <- rnorm(m, sd = sqrt(icc))[group] + rnorm(N, sd = sqrt(1 - icc))
13 y_bar <- tapply(Y, group, mean)
14 lm_fit <- lm(Y ~ 1)
15
16 test_that("CR0 and df agree with formulas", {
17 CR0 <- coef_test(lm_fit, vcov = "CR0", cluster = group, test = "Satterthwaite")
18 VCR0_f <- sum(nj^2 * (y_bar - mean(Y))^2) / sum(nj)^2
19 df0_f <- (N^2 - sum(nj^2))^2 / (N^2 * sum(nj^2) - 2 * N * sum(nj^3) + sum(nj^2)^2)
20
21 expect_equal(as.numeric(CR0$SE), sqrt(VCR0_f))
22 expect_equal(CR0$df, df0_f)
23 })
24
25 test_that("CR1 and df agree with formulas", {
26 CR1 <- coef_test(lm_fit, vcov = "CR1", cluster = group, test = "Satterthwaite")
27 VCR1_f <- (m / (m - 1)) * sum(nj^2 * (y_bar - mean(Y))^2) / sum(nj)^2
28 df1_f <- (N^2 - sum(nj^2))^2 / (N^2 * sum(nj^2) - 2 * N * sum(nj^3) + sum(nj^2)^2)
29
30 expect_equal(as.numeric(CR1$SE), sqrt(VCR1_f))
31 expect_equal(CR1$df, df1_f)
32 })
33
34 test_that("CR2 and df agree with formulas", {
35 CR2 <- coef_test(lm_fit, vcov = "CR2", cluster = group, test = "Satterthwaite")
36 VCR2_f <- sum(nj^2 * (y_bar - mean(Y))^2 / (1 - nj / N)) / sum(nj)^2
37 df2_f <- N^2 / (N^2 * sum(nj^2 / (N - nj)^2) - 2 * N * sum(nj^3 / (N - nj)^2) + sum(nj^2 / (N - nj))^2)
38
39 expect_equal(as.numeric(CR2$SE), sqrt(VCR2_f))
40 expect_equal(CR2$df, df2_f)
41 })
42
43 test_that("CR3 agrees with formula", {
44 CR3 <- coef_test(lm_fit, vcov = "CR3", cluster = group, test = "Satterthwaite")
45 VCR3_f <- sum(nj^2 * (y_bar - mean(Y))^2 / (1 - nj / N)^2) / sum(nj)^2
46 # df2_f <- N^2 / (N^2 * sum(nj^2 / (N - nj)^2) - 2 * N * sum(nj^3 / (N - nj)^2) + sum(nj^2 / (N - nj))^2)
47
48 expect_equal(as.numeric(CR3$SE), sqrt(VCR3_f))
49 # expect_equal(CR2$df, df2_f)
50 })
51
52 test_that("CR4 and df agree with formulas", {
53 CR4 <- coef_test(lm_fit, vcov = "CR4", cluster = group, test = "Satterthwaite")
54 VCR4_f <- sum(nj^2 * (y_bar - mean(Y))^2 / (1 - nj / N)) / sum(nj)^2
55 df4_f <- N^2 / (N^2 * sum(nj^2 / (N - nj)^2) - 2 * N * sum(nj^3 / (N - nj)^2) + sum(nj^2 / (N - nj))^2)
56
57 expect_equal(as.numeric(CR4$SE), sqrt(VCR4_f))
58 expect_equal(CR4$df, df4_f)
59 })