tests/testthat/test-conf_int.R

test_that("conf_int type checks", {
    dlarge <- tibble::tibble(s=1:3, y=1:3)
    ds <- tibble::tibble(Ntotal=10, ntotal=4, point=3, se=1)
    d <- tibble::tibble(n=4, point=3, se=1)
    expect_error(conf_int(.tbl="This will fail", .alpha=0.05, .interval="z"))
    expect_error(conf_int(.tbl=dlarge, .alpha = 0.05, .interval = "z"))
    expect_error(conf_int(.tbl=ds, .aplha="Now this fails", .interval="z"))
    expect_error(conf_int(.tbl=ds, .alpha=-1, .interval="z"))
    expect_error(conf_int(.tbl=ds, .alpha=1, .interval="z"))
    expect_error(conf_int(.tbl=ds, .alpha=c(0.05, 0.10), .interval="z"))
    expect_error(conf_int(.tbl=ds, .alpha=0.05, interval="Now this fails"))
})
test_that("conf_int correctness checks",{
    # Generate simple dataset for stratified and simple random samples
    ds <- tibble::tibble(Ntotal=10, ntotal=4, point=3, se=1)
    d <- tibble::tibble(n=4, point=3, se=1)

    # t and z scores for intervals
    tscore_s <- qt(1 - 0.05/2, 10-4)
    tscore <- qt(1 - 0.05/2, 4-1)
    zscore <- qnorm(1 - 0.05/2)

    # First case: using ds as input (df = 6, interval=t)
    ci <- conf_int(ds, 0.05, "t")
    expect_equal(ci$level, 95)
    expect_equal(ci$interval, "t")
    expect_equal(ci$df, 6)
    expect_equal(ci$score, tscore_s)
    expect_equal(ci$lower, 3 - tscore_s * 1)
    expect_equal(ci$upper, 3 + tscore_s * 1)

    # Second case: using ds (df = 6, interval=z)
    ci <- conf_int(ds, 0.05, "z")
    expect_equal(ci$level, 95)
    expect_equal(ci$interval, "z")
    expect_equal(ci$df, NA)
    expect_equal(ci$score, zscore)
    expect_equal(ci$lower, 3 - zscore * 1)
    expect_equal(ci$upper, 3 + zscore * 1)

    # Third case: using d as input (df = 3, interval=t)
    ci <- conf_int(d, 0.05, "t")
    expect_equal(ci$level, 95)
    expect_equal(ci$interval, "t")
    expect_equal(ci$df, 3)
    expect_equal(ci$score, tscore)
    expect_equal(ci$lower, 3 - tscore * 1)
    expect_equal(ci$upper, 3 + tscore * 1)

    # Fourth case: using d as input (df = 3, interval=z)
    ci <- conf_int(d, 0.05, "z")
    expect_equal(ci$level, 95)
    expect_equal(ci$interval, "z")
    expect_equal(ci$df, NA)
    expect_equal(ci$score, zscore)
    expect_equal(ci$lower, 3 - zscore * 1)
    expect_equal(ci$upper, 3 + zscore * 1)
})
danjdrennan/surveyr documentation built on Dec. 19, 2021, 8:08 p.m.