R/hypothesize.R
invert_test.RdTakes a test constructor function and returns the confidence set: the set of null values that are not rejected at level \(\alpha\).
invert_test(test_fn, grid, alpha = 0.05)An S3 object of class confidence_set containing:
Numeric vector of non-rejected null values
The significance level used
The confidence level (\(1 - \alpha\))
The input test function
The input grid
Hypothesis tests and confidence sets are dual: a \((1-\alpha)\) confidence set contains exactly those parameter values \(\theta_0\) for which the test of \(H_0: \theta = \theta_0\) would not reject at level \(\alpha\). This function makes that duality operational.
invert_test is the most general confidence set constructor in the
package. Any test –including user-defined tests –can be inverted. The
specialized confint() methods for wald_test and z_test give exact
analytical intervals; invert_test gives numerical intervals for
arbitrary tests at the cost of a grid search.
This function takes a function as input (test_fn) and returns a
structured result. It demonstrates the power of the hypothesis_test
abstraction: because all tests implement the same interface (pval()),
invert_test can work with any test without knowing its internals.
confint.wald_test(), confint.z_test() for analytical CIs
# Invert a Wald test to get a confidence interval
cs <- invert_test(
test_fn = function(theta) wald_test(estimate = 2.5, se = 0.8, null_value = theta),
grid = seq(0, 5, by = 0.01)
)
cs
#> Confidence set (95% level)
#> -----------------------------
#> Lower: 0.94
#> Upper: 4.06
#> Grid points in set: 313 of 501
lower(cs)
#> lower
#> 0.94
upper(cs)
#> upper
#> 4.06
# Compare with the analytical confint (should agree up to grid resolution)
confint(wald_test(estimate = 2.5, se = 0.8))
#> lower upper
#> 0.9320288 4.0679712
# Invert ANY user-defined test --no special support needed
my_test <- function(theta) {
stat <- (5.0 - theta)^2 / 2
hypothesis_test(stat = stat,
p.value = pchisq(stat, df = 1, lower.tail = FALSE), dof = 1)
}
invert_test(my_test, grid = seq(0, 10, by = 0.01))
#> Confidence set (95% level)
#> -----------------------------
#> Lower: 2.23
#> Upper: 7.77
#> Grid points in set: 555 of 1001