diff --git a/.Rbuildignore b/.Rbuildignore index bd06e02..c6995e4 100755 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,3 +1,5 @@ +^renv$ +^renv\.lock$ ^\.RData ^\.Rhistory ^README* @@ -14,3 +16,4 @@ ^\.travis\.yml$ ^\.git ^docs$ +^\.github$ diff --git a/.github/.gitignore b/.github/.gitignore new file mode 100644 index 0000000..2d19fc7 --- /dev/null +++ b/.github/.gitignore @@ -0,0 +1 @@ +*.html diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml new file mode 100644 index 0000000..2597d02 --- /dev/null +++ b/.github/workflows/R-CMD-check.yaml @@ -0,0 +1,55 @@ +# Adapted from https://github.com/r-lib/actions/tree/v2/examples +on: + push: + branches: [main, master] + pull_request: + workflow_dispatch: + +name: R-CMD-check + +permissions: read-all + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + R-CMD-check: + runs-on: ${{ matrix.config.os }} + + name: ${{ matrix.config.os }} (${{ matrix.config.r }}) + + strategy: + fail-fast: false + matrix: + config: + # - {os: macos-latest, r: 'release'} + # - {os: windows-latest, r: 'release'} + # - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} + - {os: ubuntu-latest, r: 'release'} + # - {os: ubuntu-latest, r: 'oldrel-1'} + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: ${{ matrix.config.r }} + http-user-agent: ${{ matrix.config.http-user-agent }} + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck + needs: check + + - uses: r-lib/actions/check-r-package@v2 + with: + upload-snapshots: true + build_args: 'c("--no-manual", "--compact-vignettes=gs+qpdf")' diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml new file mode 100644 index 0000000..6b97f61 --- /dev/null +++ b/.github/workflows/test-coverage.yaml @@ -0,0 +1,87 @@ +# Adapted from https://github.com/r-lib/actions/tree/v2/examples +on: + push: + branches: [main, master] + pull_request: + workflow_dispatch: + +name: test-coverage + +permissions: read-all + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test-coverage: + runs-on: ubuntu-latest + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-r@v2 + with: + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::covr, any::xml2, any::DT, any::htmltools + needs: coverage + + - name: Test coverage + run: | + cov <- covr::package_coverage( + quiet = FALSE, + clean = FALSE, + install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package") + ) + print(cov) + covr::to_cobertura(cov) + covr::report(cov, file = "coverage-report.html", browse = FALSE) + + # Per-file coverage table in the job summary + pct <- covr::percent_coverage(cov) + files <- covr::tally_coverage(cov, by = "line") + by_file <- aggregate(value ~ filename, data = files, FUN = function(v) mean(v > 0) * 100) + by_file <- by_file[order(by_file$value), ] + lines <- c( + sprintf("## Test coverage: %.2f%%", pct), + "", + "| File | Coverage |", + "|------|---------:|", + sprintf("| `%s` | %.2f%% |", by_file$filename, by_file$value) + ) + summary_file <- Sys.getenv("GITHUB_STEP_SUMMARY") + if (nzchar(summary_file)) writeLines(lines, summary_file) + shell: Rscript {0} + + - uses: codecov/codecov-action@v5 + with: + # Fail if error only when a token is configured (e.g. not on forks) + fail_ci_if_error: ${{ secrets.CODECOV_TOKEN != '' }} + files: ./cobertura.xml + plugins: noop + disable_search: true + token: ${{ secrets.CODECOV_TOKEN }} + + - name: Show testthat output + if: always() + run: | + ## -------------------------------------------------------------------- + find '${{ runner.temp }}/package' -name 'testthat.Rout*' -exec cat '{}' \; || true + shell: bash + + - name: Upload coverage report + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage-report + path: | + coverage-report.html + lib/ + cobertura.xml + ${{ runner.temp }}/package + if-no-files-found: ignore diff --git a/DESCRIPTION b/DESCRIPTION index 3e7668c..1662143 100755 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -28,7 +28,8 @@ Suggests: lme4, magrittr, rmarkdown, - testthat + testthat (>= 3.2.0), + withr Description: A mixed collection of useful and semi-useful diverse statistical functions, some of which may even be referenced in The R Primer book. See Ekstrøm, C. T. (2016). The R Primer. 2nd edition. Chapman & Hall. @@ -37,4 +38,5 @@ BugReports: https://github.com/ekstroem/MESS/issues Encoding: UTF-8 ByteCompile: true License: GPL-2 -RoxygenNote: 7.3.3 +Config/testthat/edition: 3 +Config/roxygen2/version: 8.1.1 diff --git a/NAMESPACE b/NAMESPACE index a78e10f..37321e8 100755 --- a/NAMESPACE +++ b/NAMESPACE @@ -95,53 +95,60 @@ import(geepack) import(ggformula) import(ggplot2) import(graphics) +importFrom(Rcpp,sourceCpp) importFrom(clipr,write_clip) -importFrom(grDevices,col2rgb) -importFrom(grDevices,rgb) +importFrom(grDevices, + col2rgb, + rgb +) importFrom(methods,as) -importFrom(stats,approx) -importFrom(stats,chisq.test) -importFrom(stats,coef) -importFrom(stats,complete.cases) -importFrom(stats,cor) -importFrom(stats,cor.test) -importFrom(stats,dbinom) -importFrom(stats,density) -importFrom(stats,dnorm) -importFrom(stats,drop.scope) -importFrom(stats,family) -importFrom(stats,formula) -importFrom(stats,gaussian) -importFrom(stats,glm) -importFrom(stats,integrate) -importFrom(stats,lm) -importFrom(stats,lm.fit) -importFrom(stats,model.frame) -importFrom(stats,model.matrix) -importFrom(stats,model.offset) -importFrom(stats,naprint) -importFrom(stats,p.adjust.methods) -importFrom(stats,pbinom) -importFrom(stats,pchisq) -importFrom(stats,pf) -importFrom(stats,pnorm) -importFrom(stats,predict) -importFrom(stats,qbinom) -importFrom(stats,qnorm) -importFrom(stats,rbinom) -importFrom(stats,rnorm) -importFrom(stats,rstandard) -importFrom(stats,rstudent) -importFrom(stats,sd) -importFrom(stats,simulate) -importFrom(stats,smooth.spline) -importFrom(stats,splinefun) -importFrom(stats,terms) -importFrom(stats,uniroot) -importFrom(stats,update) -importFrom(stats,update.formula) -importFrom(stats,xtabs) -importFrom(utils,capture.output) -importFrom(utils,head) -importFrom(utils,tail) +importFrom(stats, + approx, + chisq.test, + coef, + complete.cases, + cor, + cor.test, + dbinom, + density, + dnorm, + drop.scope, + family, + formula, + gaussian, + glm, + integrate, + lm, + lm.fit, + model.frame, + model.matrix, + model.offset, + naprint, + p.adjust.methods, + pbinom, + pchisq, + pf, + pnorm, + predict, + qbinom, + qnorm, + rbinom, + rnorm, + rstandard, + rstudent, + sd, + simulate, + smooth.spline, + splinefun, + terms, + uniroot, + update, + update.formula, + xtabs +) +importFrom(utils, + capture.output, + head, + tail +) useDynLib(MESS) diff --git a/R/MESS-package.R b/R/MESS-package.R index 797d55d..35f2929 100644 --- a/R/MESS-package.R +++ b/R/MESS-package.R @@ -1,6 +1,7 @@ #' @keywords internal "_PACKAGE" +#' @importFrom Rcpp sourceCpp ## usethis namespace: start #' @useDynLib MESS ## usethis namespace: end diff --git a/R/age.R b/R/age.R index a843fb6..75e23bf 100755 --- a/R/age.R +++ b/R/age.R @@ -23,9 +23,10 @@ age <- function(from, to) { age = to_lt$year - from_lt$year + age <- ifelse(to_lt$mon < from_lt$mon | (to_lt$mon == from_lt$mon & to_lt$mday < from_lt$mday), age - 1, age) + if (any(age<0)) stop("ages cannot be negative") - - ifelse(to_lt$mon < from_lt$mon | (to_lt$mon == from_lt$mon & to_lt$mday < from_lt$mday), age - 1, age) + age } diff --git a/R/auc.R b/R/auc.R index f4310d8..9d9a0cf 100755 --- a/R/auc.R +++ b/R/auc.R @@ -65,6 +65,11 @@ function(x, y, from = min(x, na.rm=TRUE), to = max(x, na.rm=TRUE), type=c("linea if (length(unique(x)) < 2) return(NA) + # sort X + o <- order(x) + x <- x[o] + y <- y[o] + if (type=="linear") { ## Default option @@ -85,23 +90,23 @@ function(x, y, from = min(x, na.rm=TRUE), to = max(x, na.rm=TRUE), type=c("linea # Get the order of the first occurrence of unique values in sorted x # This works because the new points are added to the end of the vector unique_order <- order(match(sort(unique(newx)), newx)) - + # Get the unique sorted x values x_sorted_unique <- sort(unique(newx)) - + # Match the sorted unique x values to their first occurrence in x match_indices <- match(x_sorted_unique, newx) - + # Reorder y accordingly y_sorted <- newy[match_indices] - + newx <- x_sorted_unique newy <- y_sorted values <- approx(newx, newy, xout = sort(unique(c(from, to, newx[newx > from & newx < to]))), ...) res <- 0.5 * sum(diff(values$x) * (abs(values$y[-1]) + abs(values$y[-length(values$y)]))) } - + } else { ## If it is not a linear approximation if (absolutearea) myfunction <- function(z) { abs(splinefun(x, y, method="natural")(z)) } diff --git a/R/fitted.geese.R b/R/fitted.geese.R index 2a2cd0b..8103b8d 100755 --- a/R/fitted.geese.R +++ b/R/fitted.geese.R @@ -4,7 +4,11 @@ fitted.geese <- function(object, ...) { # Get the linear predictor glmcall <- object$call - glmcall$id <- glmcall$jack <- glmcall$control <- glmcall$corstr <- glmcall$waves <- glmcall$zcor <- glmcall$std.err <- glmcall$scale.fix <- glmcall$scale.value<- glmcall$z <- NULL + + drop <- c("id", "jack", "control", "corstr", "waves", "zcor", + "std.err", "scale.fix", "scale.value", "z", "family") + glmcall[drop] <- NULL + glmcall[[1]] <- as.name("model.frame") mf <- eval(glmcall, parent.frame()) @@ -14,16 +18,16 @@ fitted.geese <- function(object, ...) { offset <- model.offset(mf) - if (is.null(offset)) + if (is.null(offset)) offset <- rep(0, N) value <- object - - + + value$offset <- offset - if (is.null(value$offset)) + if (is.null(value$offset)) value$linear.predictors <- X %*% object$beta - else value$linear.predictors <- value$offset + X %*% + else value$linear.predictors <- value$offset + X %*% object$beta @@ -32,3 +36,23 @@ fitted.geese <- function(object, ...) { fitted.values } + +#' @export +family.geese <- function(object, ...) { + family <- object$call$family + if (is.null(family)) + tryCatch({ + family_defaults <- formals(eval(object$call[[1]]))$family # attempt to find defaults of call + if (is.language(family_defaults)) { + eval(family_defaults) + } else { + family_defaults + } + }, error = function(e) { + stats::gaussian() + }) + else { + eval(family) + } + +} diff --git a/man/MESS-package.Rd b/man/MESS-package.Rd index 470b2b9..0bc4345 100644 --- a/man/MESS-package.Rd +++ b/man/MESS-package.Rd @@ -19,6 +19,11 @@ Useful links: \author{ \strong{Maintainer}: Claus Thorn Ekstrøm \email{claus@rprimer.dk} +Authors: +\itemize{ + \item Claus Thorn Ekstrøm \email{claus@rprimer.dk} +} + Other contributors: \itemize{ \item Niels Aske Lundtorp Olsen \email{nalo@dtu.dk} [contributor] diff --git a/man/pairwise_distance_correlation.Rd b/man/pairwise_distance_correlation.Rd new file mode 100644 index 0000000..7090206 --- /dev/null +++ b/man/pairwise_distance_correlation.Rd @@ -0,0 +1,31 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/RcppExports.R +\name{pairwise_distance_correlation} +\alias{pairwise_distance_correlation} +\title{Compute pairwise distance correlation metrics of each column to a vector} +\usage{ +pairwise_distance_correlation(x, y) +} +\arguments{ +\item{x}{A matrix. The number of rows should match the length of the vector y} + +\item{y}{A vector} +} +\value{ +A vector with the same length as the number of columns in x. Each element contains the pairwise distance correlation to y. +} +\description{ +Fast computation of pairwise distance correlations. +} +\details{ +Note: To get the same result as from the energy package you need to take the square root of the results here. +} +\examples{ +y <- rnorm(100) +x <- matrix(rnorm(100 * 10), ncol = 10) +pairwise_distance_correlation(x, y) + +} +\author{ +Claus Ekstrom +} diff --git a/tests/testthat/helper-fixtures.R b/tests/testthat/helper-fixtures.R new file mode 100644 index 0000000..d9e4a5d --- /dev/null +++ b/tests/testthat/helper-fixtures.R @@ -0,0 +1,99 @@ +# Shared fixtures for the MESS test suite. +# +# Fixtures are built by functions (not at file top level) so that every test +# creates its own data and random-number state never leaks between tests. + +# 14-person, 3-generation pedigree used by the kinship / pedigree tests. +# +# founders: 1, 2, 3, 4, 11, 12 +# 5, 6 children of 1 x 2 +# 7, 8 children of 3 x 4 +# 9 child of 3 x 6 +# 10 child of 7 x 2 +# 13 child of 11 x 12 +# 14 child of 10 x 13 +make_pedigree <- function() { + ped <- data.frame( + id = 1:14, + dad = c(0, 0, 0, 0, 1, 1, 3, 3, 3, 7, 0, 0, 11, 10), + mom = c(0, 0, 0, 0, 2, 2, 4, 4, 6, 2, 0, 0, 12, 13), + sex = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2) + ) + kinship2::pedigree(ped$id, ped$dad, ped$mom, ped$sex) +} + +# Two nuclear families (parents + two children) as a pedigreeList. +# `id` lets the tests reuse the same ids in both families. +make_two_families <- function(id = c(1:4, 11:14)) { + kinship2::pedigree( + id = id, + dadid = c(NA, NA, id[1], id[1], NA, NA, id[5], id[5]), + momid = c(NA, NA, id[2], id[2], NA, NA, id[6], id[6]), + sex = c(1, 2, 1, 2, 1, 2, 1, 2), + famid = rep(c("A", "B"), each = 4) + ) +} + +# Clustered binary outcome data for the GEE tests (drop1, QIC, geekin). +# 20 clusters of size 4 with a cluster-level random intercept. +make_gee_data <- function(seed = 1) { + withr::local_seed(seed) + n_clusters <- 20 + cluster_size <- 4 + id <- rep(seq_len(n_clusters), each = cluster_size) + age <- rep(seq_len(cluster_size), times = n_clusters) + x1 <- stats::rnorm(n_clusters * cluster_size) + u <- rep(stats::rnorm(n_clusters, sd = 0.5), each = cluster_size) + p <- stats::plogis(-0.5 + 0.8 * x1 + 0.3 * age + u) + y <- stats::rbinom(length(p), 1, p) + data.frame(id = id, y = y, x1 = x1, age = age) +} + +# Poisson GEE on warpbreaks with 18 clusters of 3. The model call refers only +# to objects on the search path, so drop1()'s internal update() can refit it. +fit_warpbreaks_geeglm <- function() { + geepack::geeglm( + breaks ~ wool + tension, id = rep(1:18, each = 3), data = warpbreaks, + family = poisson, corstr = "exchangeable" + ) +} + +# Expected correlation for a nuclear family under the extended model: +# spouses: rho, parent-child: theta * (1 + rho) / 2, +# siblings: theta^2 * (1 + rho) / 2, all variances 1. +nuclear_expected <- function(rho, theta) { + pc <- theta * (1 + rho) / 2 + sib <- theta^2 * (1 + rho) / 2 + m <- matrix(c( + 1, rho, pc, pc, + rho, 1, pc, pc, + pc, pc, 1, sib, + pc, pc, sib, 1 + ), 4, 4, dimnames = list(as.character(1:4), as.character(1:4))) + m +} + +# Data for the feature.test() tests: y depends only on the first column of x. +# Tests pass a numeric `s`, which fixes lambda and skips the (random) +# cross-validation. +make_feature_data <- function() { + withr::local_seed(42) + x <- matrix(rnorm(20 * 5), nrow = 20) + y <- rnorm(20, mean = 2 * x[, 1]) + list(x = x, y = y) +} + +# A block-diagonal matrix of ones (one block per cluster) gives a single +# correlation parameter shared by all within-cluster pairs, i.e. geekin() +# reproduces geeglm() with an exchangeable working correlation. +exchangeable_varlist <- function(n_clusters = 20, cluster_size = 4) { + kronecker(diag(n_clusters), matrix(1, cluster_size, cluster_size)) +} + +# Reference power for the two-sided test: probability under pa of the exact +# rejection region of stats::binom.test() at level 0.05. +binom_test_power <- function(n, p0, pa) { + x <- 0:n + reject <- vapply(x, function(k) binom.test(k, n, p0)$p.value <= 0.05, logical(1)) + sum(dbinom(x[reject], n, pa)) +} diff --git a/tests/testthat/test-RcppExports-matrix.R b/tests/testthat/test-RcppExports-matrix.R new file mode 100644 index 0000000..7d6abaa --- /dev/null +++ b/tests/testthat/test-RcppExports-matrix.R @@ -0,0 +1,91 @@ +# Matrix helpers implemented in C++ (src/), cross-checked against base R. + +test_that("add_torows() adds a vector to every row", { + A <- matrix(1:12, ncol = 3) + expect_equal(add_torows(A, c(1, 2, 3)), t(t(A) + c(1, 2, 3))) + expect_equal(add_torows(matrix(5), 2), matrix(7)) +}) + +test_that("add_torows() errors when the vector length differs from ncol", { + expect_error(add_torows(matrix(1:12, ncol = 3), c(1, 2)), "Length of v does not match columns") +}) + +test_that("colCumSum() equals apply(m, 2, cumsum)", { + expect_equal(colCumSum(matrix(1:6, 2)), matrix(c(1, 3, 3, 7, 5, 11), 2)) + withr::local_seed(1) + m <- matrix(rnorm(20), nrow = 5) + expect_equal(colCumSum(m), apply(m, 2, cumsum)) + expect_equal(colCumSum(matrix(1:3, nrow = 1)), matrix(1:3, nrow = 1)) +}) + +test_that("cmd() equals 1 - tr(AB) / (||A||_F ||B||_F)", { + m1 <- matrix(1, 4, 4) + m2 <- matrix(c(1, 0, .5, .5, 0, 1, .5, .5, .5, .5, 1, .5, .5, .5, .5, 1), 4) + m3 <- matrix(c(1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), 4) + cmd_r <- function(a, b) 1 - sum(diag(a %*% b)) / (norm(a, "F") * norm(b, "F")) + + expect_equal(cmd(m1, m1), 0) + expect_equal(cmd(m1, m2), cmd_r(m1, m2)) + expect_equal(cmd(m2, m3), cmd_r(m2, m3)) + # documented example values + expect_equal(cmd(m1, m2), 0.1174774, tolerance = 1e-6) + expect_equal(cmd(m2, m3), 0.3594874, tolerance = 1e-6) +}) + +test_that("cmd() errors for matrices of different dimensions", { + expect_error(cmd(matrix(1:4, 2), matrix(1:9, 3)), "must have the same dimensions") +}) + +test_that("qdiag() equals diag()", { + withr::local_seed(2) + m <- matrix(rnorm(16), nrow = 4) + expect_equal(qdiag(m), diag(m)) + expect_equal(qdiag(matrix(5)), 5) +}) + +test_that("qdiag() errors for non-square or non-matrix input", { + expect_error(qdiag(matrix(1:6, nrow = 2)), "must be square") + expect_error(qdiag(matrix(1:6, nrow = 3)), "must be square") + expect_error(qdiag(1:3), "Not a matrix") +}) + +test_that("quadform() computes t(x) M x and its variants", { + x <- matrix(1:4, ncol = 2) + M <- matrix(c(4, 1, 1, 3), ncol = 2) + + expect_equal(quadform(x, M), t(x) %*% M %*% x) + expect_equal(quadform(x, M, invertM = TRUE), t(x) %*% solve(M) %*% x) + expect_equal(quadform(t(x), M, transposex = TRUE), t(x) %*% M %*% x) + expect_equal(quadform(t(x), M, invertM = TRUE, transposex = TRUE), t(x) %*% solve(M) %*% x) + expect_equal(quadform(matrix(2), matrix(3)), matrix(12)) +}) + +test_that("quadform() errors for non-conformable input", { + # the message comes from Armadillo, so only the error is checked + expect_error(quadform(matrix(1:6, nrow = 2), matrix(1:9, nrow = 3))) +}) + +test_that("repmat() tiles a matrix", { + m <- matrix(1:6, ncol = 3) + expect_equal(repmat(m, 2), rbind(m, m)) + expect_equal(repmat(m, 2, 3), cbind(rbind(m, m), rbind(m, m), rbind(m, m))) +}) + +test_that("repmat() errors for fewer than one replicate", { + m <- matrix(1:6, ncol = 3) + expect_error(repmat(m, 0, 1), "Number of rows to replicate must be >= 1") + expect_error(repmat(m, 1, 0), "Number of columns to replicate must be >= 1") +}) + +test_that("tracemp() equals tr(t(A) B)", { + A <- matrix(1:12, ncol = 3) + expect_equal(tracemp(A, A), 650) # sum(A^2) = sum((1:12)^2) + withr::local_seed(3) + A <- matrix(rnorm(12), ncol = 3) + B <- matrix(rnorm(12), ncol = 3) + expect_equal(tracemp(A, B), sum(diag(t(A) %*% B))) +}) + +test_that("tracemp() errors for matrices of different dimensions", { + expect_error(tracemp(matrix(1:4, 2), matrix(1:9, 3)), "must have the same dimensions") +}) diff --git a/tests/testthat/test-RcppExports-stats.R b/tests/testthat/test-RcppExports-stats.R new file mode 100644 index 0000000..35ee36f --- /dev/null +++ b/tests/testthat/test-RcppExports-stats.R @@ -0,0 +1,179 @@ +# Statistical helpers implemented in C++ (src/), checked against hand-computed +# values or base R equivalents. + +test_that("bin() counts values in equal-width bins", { + # bins [0,3), [3,6), [6,9), [9,12) + res <- bin(c(1, 2, 5, 6, 9), 3) + expect_named(res, c("counts", "origin", "width", "missing", "last_bin_is_missing")) + expect_equal(res$counts, c(2, 1, 1, 1)) + expect_equal(res$origin, 0) + expect_equal(res$width, 3) + expect_equal(res$missing, 0) + expect_false(res$last_bin_is_missing) +}) + +test_that("bin() drops values below origin", { + # bins [2,5), [5,8), [8,11); the value 1 is dropped + res <- bin(c(1, 2, 5, 6, 9), 3, origin = 2) + expect_equal(res$counts, c(1, 2, 1)) + expect_equal(res$origin, 2) +}) + +test_that("bin() counts missing values and optionally appends them", { + x <- c(1, 2, NA, 3, NaN, 4) + + res <- bin(x, 2, missinglast = TRUE) + expect_equal(res$counts, c(1, 2, 1, 2)) + expect_equal(res$missing, 2) + expect_true(res$last_bin_is_missing) + + res <- bin(x, 2) + expect_equal(res$counts, c(1, 2, 1)) + expect_equal(res$missing, 2) +}) + +test_that("bin() errors for a non-positive width", { + expect_error(bin(1:5, 0), "width must be positive") + expect_error(bin(1:5, -1), "width must be positive") +}) + +test_that("cumsumbinning() starts a new group before the threshold is exceeded", { + x <- c(3, 4, 5, 12, 1, 5, 3) + expect_equal(cumsumbinning(x, 10), c(1, 1, 2, 3, 4, 4, 4)) + expect_equal(cumsumbinning(x, 10, cutwhenpassed = TRUE), c(1, 1, 1, 2, 3, 3, 3)) +}) + +test_that("cumsumbinning() caps the group size with maxgroupsize", { + x <- c(3, 4, 5, 12, 1, 5, 3) + expect_equal(cumsumbinning(x, 10, maxgroupsize = 2), c(1, 1, 2, 3, 4, 4, 5)) + expect_equal(cumsumbinning(x, 10, cutwhenpassed = TRUE, maxgroupsize = 2), c(1, 1, 2, 2, 3, 3, 4)) + expect_error(cumsumbinning(x, 10, maxgroupsize = 0), "maxgroupsize should be larger than 0") +}) + +test_that("dCor() is 1 for a linear relationship", { + x <- matrix(1:10) + expect_equal(dCor(x, 2 * x), 1) + expect_equal(dCor(x, x), 1) +}) + +test_that("dCov() and dCor() error for different numbers of rows", { + expect_error(dCov(matrix(1:10), matrix(1:8)), "same number of rows") + expect_error(dCor(matrix(1:10), matrix(1:8)), "same number of rows") +}) + +test_that("pairwise_distance_correlation() returns dCor^2 per column", { + withr::local_seed(10) + y <- rnorm(30) + x <- matrix(rnorm(30 * 4), ncol = 4) + expected <- vapply(1:4, function(k) dCor(x[, k, drop = FALSE], matrix(y))^2, numeric(1)) + + expect_equal(as.numeric(pairwise_distance_correlation(x, y)), expected) +}) + +test_that("pairwise_distance_correlation() errors on mismatched rows", { + # the message comes from Armadillo, so only the error is checked + expect_error(pairwise_distance_correlation(matrix(1:10, ncol = 2), 1:3)) +}) + +test_that("filldown() carries the last non-missing value forward", { + expect_equal( + filldown(c(1:5, "Howdy", NA, NA, 2:3, NA)), + c("1", "2", "3", "4", "5", "Howdy", "Howdy", "Howdy", "2", "3", "3") + ) + expect_equal(filldown(c(NA, NA, NA, 3:5)), c(NA, NA, NA, 3, 4, 5)) + expect_equal(filldown(c(NA, 1, NA, 2)), c(NA, 1, 1, 2)) + expect_equal(filldown(c(1, 2, 3)), c(1, 2, 3)) + expect_equal(filldown(c(TRUE, NA, FALSE, NA)), c(TRUE, TRUE, FALSE, FALSE)) +}) + +test_that("hwe_frequencies() computes allele and genotype frequencies", { + # Genotypes 1/1, 1/2, 2/2, 2/1, 1/1, 2/2: p = q = 0.5 + res <- hwe_frequencies(c(1, 1, 2, 2, 1, 2), c(1, 2, 2, 1, 1, 2)) + + expect_named(res, c("allele_freq", "genotype_freq", "obs_genotype", "available_genotypes", "unique_alleles")) + expect_equal(res$allele_freq, c(0.5, 0.5)) + expect_equal(res$genotype_freq, c(0.25, 0.5, 0.25)) # p^2, 2pq, q^2 + expect_equal(res$obs_genotype, c(2L, 2L, 2L)) + expect_equal(res$available_genotypes, 6L) + expect_equal(res$unique_alleles, 2L) +}) + +test_that("hwe_frequencies() pads allele frequencies to min_alleles", { + res <- hwe_frequencies(c(1, 1, 2, 2, 1, 2), c(1, 2, 2, 1, 1, 2), min_alleles = 4) + expect_equal(res$allele_freq, c(0.5, 0.5, 0, 0)) +}) + +test_that("hwe_frequencies() errors for alleles of different lengths", { + expect_error(hwe_frequencies(c(1, 2, 3), c(1, 2)), "lengths of allele1 and allele2 must match") +}) + +test_that("ks_cumtest() computes the maximal cumulative difference", { + withr::local_seed(1) + res <- ks_cumtest(1:6, B = 1000) + + # max |cumsum(x) / 21 - (1:6) / 6| is reached at k = 3: |6/21 - 1/2| = 3/14 + expect_s3_class(res, "htest") + expect_equal(unname(res$statistic), 3 / 14) + expect_equal(res$p.value, 0.1038961, tolerance = 1e-6) +}) + +test_that("ks_cumtest() uses prob as the null distribution", { + withr::local_seed(1) + res <- ks_cumtest(1:6, B = 100, prob = c(5, 1, 1, 1, 1, 1) / 10) + # max |cumsum(1:6) / 21 - cumsum(prob)| is reached at k = 2: |3/21 - 6/10| + expect_equal(unname(res$statistic), 6 / 10 - 3 / 21) +}) + +test_that("ks_cumtest() validates its input", { + expect_error(ks_cumtest(1:6, B = 100, prob = c(1, 1, 1)), "lengths of x and prob must match") + expect_error(ks_cumtest(1:6, B = 100, prob = c(1, 1, 1, 1, 1, 0)), "must be positive") + expect_error(ks_cumtest(1:6, B = 0), "must be greater than 0") +}) + +test_that("maximum_subarray() finds the contiguous subarray with the largest sum", { + expect_equal(maximum_subarray(1:4), list(sum = 10, start = 1, end = 4)) + expect_equal(maximum_subarray(c(-2, 1, -3, 4, -1, 2, 1, -5, 4)), list(sum = 6, start = 4, end = 7)) + expect_equal(maximum_subarray(c(-5, -2, -8, -1, -9)), list(sum = -1, start = 4, end = 4)) + expect_equal(maximum_subarray(7), list(sum = 7, start = 1, end = 1)) +}) + +test_that("mfastLmCpp() fits one simple linear regression per column", { + X <- cbind(1:6, c(2, 1, 4, 3, 6, 5)) + y <- c(1, 3, 2, 5, 4, 6) + slope <- function(fit) unname(summary(fit)$coefficients[2, 1:3]) + + res <- mfastLmCpp(y, X) + expect_named(res, c("coefficients", "stderr", "tstat")) + expect_equal(unlist(res[1, ]), slope(lm(y ~ X[, 1])), ignore_attr = TRUE) + expect_equal(unlist(res[2, ]), slope(lm(y ~ X[, 2])), ignore_attr = TRUE) + + res <- mfastLmCpp(y, X, addintercept = FALSE) + expect_equal( + unlist(res[1, ]), + unname(summary(lm(y ~ X[, 1] - 1))$coefficients[1, 1:3]), + ignore_attr = TRUE + ) +}) + +test_that("pairwise_Schur_product() multiplies all pairs of columns", { + X <- cbind(rep(1, 4), 1:4, 4:1) + + expect_equal( + unname(pairwise_Schur_product(X)), + cbind(X[, 1] * X[, 2], X[, 1] * X[, 3], X[, 2] * X[, 3]) + ) + expect_equal( + unname(pairwise_Schur_product(X, self = TRUE)), + cbind(X[, 1]^2, X[, 1] * X[, 2], X[, 1] * X[, 3], X[, 2]^2, X[, 2] * X[, 3], X[, 3]^2) + ) + expect_equal(dim(pairwise_Schur_product(matrix(1:4))), c(4, 0)) +}) + +test_that("pairwise_combination_indices() lists all index pairs", { + expect_equal(unname(pairwise_combination_indices(3)), matrix(c(1, 1, 2, 2, 3, 3), ncol = 2)) + expect_equal( + unname(pairwise_combination_indices(3, self = TRUE)), + matrix(c(1, 1, 1, 2, 2, 3, 1, 2, 3, 2, 3, 3), ncol = 2) + ) + expect_error(pairwise_combination_indices(0), "must be greater than 0") +}) diff --git a/tests/testthat/test-adaptive.weights.R b/tests/testthat/test-adaptive.weights.R new file mode 100644 index 0000000..6fe90c9 --- /dev/null +++ b/tests/testthat/test-adaptive.weights.R @@ -0,0 +1,45 @@ +make_aw_data <- function(n = 50, p = 5, seed = 1) { + withr::local_seed(seed) + x <- matrix(rnorm(n * p), nrow = n) + list(x = x, y = rnorm(n, mean = x[, 1])) +} + +univariate_weights <- function(x, y, nu = 1) { + apply(x, 2, function(xi) 1 / abs(coef(lm(y ~ xi))[[2]])^nu) +} + +test_that("multivariate weights are 1/|beta| from the joint lm() fit", { + d <- make_aw_data() + res <- adaptive.weights(d$x, d$y) + + expect_named(res, c("weights", "nu")) + expect_equal(res$nu, 1) + expect_equal(unname(res$weights), unname(1 / abs(coef(lm(d$y ~ d$x))[-1]))) +}) + +test_that("univariate weights are 1/|beta| from one lm() fit per column", { + d <- make_aw_data() + res <- adaptive.weights(d$x, d$y, weight.method = "univariate") + + expect_equal(unname(res$weights), univariate_weights(d$x, d$y)) +}) + +test_that("nu is used as the exponent of the weights", { + d <- make_aw_data() + w1 <- adaptive.weights(d$x, d$y, nu = 1)$weights + + expect_equal(adaptive.weights(d$x, d$y, nu = 2)$weights, w1^2) + expect_equal(unname(adaptive.weights(d$x, d$y, nu = 0)$weights), rep(1, 5)) +}) + +test_that("univariate weights are used with a warning when p >= n", { + d <- make_aw_data(n = 5, p = 6, seed = 2) + + expect_warning(res <- adaptive.weights(d$x, d$y), "using univariate weight method since p>n") + expect_equal(unname(res$weights), univariate_weights(d$x, d$y)) +}) + +test_that("an invalid weight.method is an error", { + d <- make_aw_data() + expect_error(adaptive.weights(d$x, d$y, weight.method = "bogus"), "should be one of") +}) diff --git a/tests/testthat/test-age.R b/tests/testthat/test-age.R new file mode 100644 index 0000000..2630b76 --- /dev/null +++ b/tests/testthat/test-age.R @@ -0,0 +1,29 @@ +test_that("age() matches the documented example", { + born <- c("1971-08-18", "2000-02-28", "2001-12-20") + expect_equal(age(born, "2016-08-28"), c(45, 16, 14)) +}) + +test_that("age() is zero on the birth date and increments on the birthday", { + expect_equal(age("2000-01-01", "2000-01-01"), 0) + expect_equal(age("2000-05-10", c("2001-05-09", "2001-05-10")), c(0, 1)) +}) + +test_that("age() handles a 29 February birth date", { + expect_equal(age("2000-02-29", c("2001-02-28", "2001-03-01", "2004-02-29")), c(0, 1, 4)) +}) + +test_that("age() accepts Date input", { + expect_equal(age(as.Date("1990-05-10"), as.Date("2020-05-10")), 30) +}) + +test_that("age() errors when 'to' is before 'from' in an earlier year", { + expect_error(age("2016-01-01", "2015-01-01"), "ages cannot be negative") +}) + +test_that("age() errors when 'to' is before 'from' within the same year", { + expect_error(age("2016-06-01", "2016-01-01"), "ages cannot be negative") +}) + +test_that("age() errors when 'to' is before 'from' within the same year/month", { + expect_error(age("2016-06-03", "2016-06-01"), "ages cannot be negative") +}) diff --git a/tests/testthat/test-auc.R b/tests/testthat/test-auc.R new file mode 100755 index 0000000..2c134e9 --- /dev/null +++ b/tests/testthat/test-auc.R @@ -0,0 +1,32 @@ +test_that("Produces validated results", { + expect_equal(auc(1:4, c(0, 1, 1, 5)), 4.5) + expect_equal(auc(1:4, -c(0, 1, 1, 5)), -4.5) + expect_equal(auc(1:4, -c(0, 1, 1, 5), absolutearea=TRUE), 4.5) + expect_equal(auc(0:4, c(0, 0, 1, -1, 0)), 0) + expect_equal(auc(0:4, c(0, 0, 1, -1, 0), absolutearea=TRUE), 1.5) + expect_equal(auc(0:4, c(0, 0, 1, -1, 0), absolutearea=TRUE, subdivisions =150), 1.5) + expect_equal(auc(0:4, c(0, 0, 1, -1, 0), from=0, rule=2, type="spline", yleft=.5), -0.214285, tolerance=0.00001) +}) + +test_that("auc() with type = 'spline' integrates the natural spline", { + x <- 0:4 + y <- c(0, 0, 1, -1, 0) + f <- splinefun(x, y, method = "natural") + + expect_equal( + auc(x, y, type = "spline", absolutearea = TRUE), + integrate(function(z) abs(f(z)), 0, 4)$value + ) + expect_equal(auc(x, y, type = "spline", from = 1, to = 3), integrate(f, 1, 3)$value) +}) + +test_that("auc() returns NA for a single x value", { + expect_identical(auc(2, 1), NA) +}) + +test_that("auc() with absolutearea = TRUE handles unsorted x values", { + expect_equal( + auc(c(4, 0, 1, 2, 3), c(0, 0, 0, 1, -1), absolutearea = TRUE), + auc(c(0, 1, 2, 3), c(0, 1, -1, 0), absolutearea = TRUE) + ) +}) diff --git a/tests/testthat/test-categorize.R b/tests/testthat/test-categorize.R new file mode 100644 index 0000000..90402a5 --- /dev/null +++ b/tests/testthat/test-categorize.R @@ -0,0 +1,13 @@ +test_that("categorize() with bare names equals table()", { + expect_equal(categorize(esoph, alcgp, agegp), table(esoph$alcgp, esoph$agegp), ignore_attr = TRUE) + expect_equal(categorize(esoph, alcgp), table(esoph$alcgp), ignore_attr = TRUE) +}) + +test_that("categorize() with a formula equals xtabs()", { + expect_equal(categorize(esoph, ~ alcgp + agegp), xtabs(~ alcgp + agegp, data = esoph), ignore_attr = "call") + expect_equal(categorize(esoph, ncases ~ alcgp), xtabs(ncases ~ alcgp, data = esoph), ignore_attr = "call") +}) + +test_that("categorize() errors for an unknown variable", { + expect_error(categorize(esoph, nonexistentvariable), "not found") +}) diff --git a/tests/testthat/test-chisq_test.R b/tests/testthat/test-chisq_test.R new file mode 100644 index 0000000..b0b7e5b --- /dev/null +++ b/tests/testthat/test-chisq_test.R @@ -0,0 +1,75 @@ +# 2x2 table with row sums 20, 10 and column sums 16, 14 (N = 30) +chisq_table <- matrix(c(12, 4, 8, 6), 2) + +pearson_statistic <- function(x) { + e <- outer(rowSums(x), colSums(x)) / sum(x) + sum((x - e)^2 / e) +} + +test_that("monte_carlo_chisq_test() returns the Pearson statistic and expected counts", { + withr::local_seed(1) + res <- monte_carlo_chisq_test(chisq_table, B = 1000) + + expect_s3_class(res, "htest") + expect_named(res, c("statistic", "parameter", "p.value", "method", "data.name", "observed", "expected")) + expect_equal(unname(res$statistic), pearson_statistic(chisq_table)) + expect_equal(res$expected, outer(c(20, 10), c(16, 14)) / 30) + expect_equal(res$observed, chisq_table) + expect_equal(res$parameter, c(B = 1000)) + expect_equal(res$data.name, "chisq_table") + expect_match(res$method, "fixed N \\(total number of observations\\)") +}) + +test_that("monte_carlo_chisq_test() p-values are reproducible with a fixed seed", { + withr::local_seed(1) + p1 <- monte_carlo_chisq_test(chisq_table, B = 1000)$p.value + withr::local_seed(1) + p2 <- monte_carlo_chisq_test(chisq_table, B = 1000)$p.value + + expect_identical(p1, p2) + expect_equal(p1, 0.3486513, tolerance = 1e-6) +}) + +test_that("monte_carlo_chisq_test() with margin = 'rows' fixes the row margins", { + withr::local_seed(1) + res <- monte_carlo_chisq_test(chisq_table, margin = "rows", B = 1000) + + expect_equal(unname(res$statistic), 15 / 14) + expect_equal(res$p.value, 0.3736264, tolerance = 1e-6) + expect_match(res$method, "fixed row margins") +}) + +test_that("monte_carlo_chisq_test() with margin = 'both' matches chisq.test(simulate.p.value = TRUE)", { + withr::local_seed(3) + res <- monte_carlo_chisq_test(chisq_table, margin = "both", B = 1000) + withr::local_seed(3) + ref <- chisq.test(chisq_table, correct = FALSE, simulate.p.value = TRUE, B = 1000) + + expect_equal(res$p.value, ref$p.value) + expect_equal(unname(res$statistic), unname(ref$statistic)) + expect_match(res$method, "fixed row AND column margins") +}) + +test_that("monte_carlo_chisq_test() accepts a data frame", { + withr::local_seed(1) + res <- monte_carlo_chisq_test(as.data.frame(chisq_table), B = 100) + expect_equal(unname(res$statistic), 15 / 14) +}) + +test_that("monte_carlo_chisq_test() validates its input", { + expect_error(monte_carlo_chisq_test(matrix(c(-1, 4, 8, 6), 2), B = 10), "nonnegative and finite") + expect_error(monte_carlo_chisq_test(matrix(c(1, NA, 8, 6), 2), B = 10), "nonnegative and finite") + expect_error(monte_carlo_chisq_test(matrix(0, 2, 2), B = 10), "at least one entry") + expect_error(monte_carlo_chisq_test(matrix(1:3, 1), B = 10), "2-way tables") + expect_error(monte_carlo_chisq_test(1:4, B = 10), "convertible with a matrix") + expect_error(monte_carlo_chisq_test(chisq_table, margin = "cols"), "should be one of") +}) + +test_that("monte_carlo_chisq_test() rejects zero margins when they are fixed", { + zero_row <- matrix(c(0, 4, 0, 6), 2) + zero_col <- matrix(c(0, 0, 4, 6), 2) + + expect_error(monte_carlo_chisq_test(zero_row, margin = "rows", B = 10), "row marginals") + expect_error(monte_carlo_chisq_test(zero_row, margin = "both", B = 10), "row marginals") + expect_error(monte_carlo_chisq_test(zero_col, margin = "both", B = 10), "column marginals") +}) diff --git a/tests/testthat/test-clipit.R b/tests/testthat/test-clipit.R new file mode 100644 index 0000000..1f91ff7 --- /dev/null +++ b/tests/testthat/test-clipit.R @@ -0,0 +1,16 @@ +test_that("clipit() writes the dput() representation to the clipboard", { + captured <- NULL + local_mocked_bindings( + write_clip = function(content, ...) { + captured <<- content + invisible(content) + }, + .package = "clipr" + ) + + clipit(c(1, 2, 3)) + expect_equal(captured, "c(1, 2, 3)") + + clipit(c("a", "b")) + expect_equal(captured, "c(\"a\", \"b\")") +}) diff --git a/tests/testthat/test-colorfunctions.R b/tests/testthat/test-colorfunctions.R new file mode 100644 index 0000000..bae90ad --- /dev/null +++ b/tests/testthat/test-colorfunctions.R @@ -0,0 +1,39 @@ +test_that("col.shade() mixes colours towards black", { + expect_equal(col.shade("blue", 0), "#0000FFFF") + expect_equal(col.shade("blue", 1), "#000000FF") + expect_equal(col.shade(c("blue", "red"), 0.5), c("#00007FFF", "#7F0000FF")) +}) + +test_that("col.shade() keeps an existing alpha channel", { + expect_equal(col.shade("#0000FF80", 0.5), "#00007F80") +}) + +test_that("col.tint() mixes colours towards white", { + expect_equal(col.tint("blue", 0), "#FFFFFFFF") + expect_equal(col.tint("blue", 1), "#0000FFFF") + expect_equal(col.tint(c("blue", "red"), 0.5), c("#7F7FFFFF", "#FF7F7FFF")) +}) + +test_that("col.alpha() sets the alpha channel", { + expect_equal(col.alpha("blue", 0), "#0000FF00") + expect_equal(col.alpha("blue", 1), "#0000FFFF") + expect_equal(col.alpha(c("blue", "red"), 0.5), c("#0000FF80", "#FF000080")) + # an existing alpha channel is overwritten + expect_equal(col.alpha("#0000FF20", 1), "#0000FFFF") +}) + +test_that("colour functions error when col is missing", { + expect_error(col.shade(), "a vector of colours is missing") + expect_error(col.tint(), "a vector of colours is missing") + expect_error(col.alpha(), "a vector of colours is missing") +}) + +test_that("colour functions error for out-of-range arguments", { + expect_error(col.shade("blue", -0.1), "shade must be between 0 and 1") + expect_error(col.shade("blue", 1.1), "shade must be between 0 and 1") + # col.tint's message wrongly says "shade" (B02), so only the range is matched + expect_error(col.tint("blue", -0.1), "between 0 and 1") + expect_error(col.tint("blue", 1.1), "between 0 and 1") + expect_error(col.alpha("blue", -0.1), "alpha must be between 0 and 1") + expect_error(col.alpha("blue", 1.1), "alpha must be between 0 and 1") +}) diff --git a/tests/testthat/test-common.shared.R b/tests/testthat/test-common.shared.R new file mode 100644 index 0000000..167acfa --- /dev/null +++ b/tests/testthat/test-common.shared.R @@ -0,0 +1,33 @@ +test_that("common.shared() gives a matrix of ones for a pedigree", { + ped <- make_pedigree() + result <- common.shared(ped) + + ids <- as.character(1:14) + expect_identical(result, matrix(1, 14, 14, dimnames = list(ids, ids))) +}) + +test_that("common.shared() handles a single-person pedigree", { + one <- kinship2::pedigree(1, NA, NA, "male") + expect_identical(common.shared(one), matrix(1, 1, 1, dimnames = list("1", "1"))) +}) + +test_that("common.shared() errors on duplicated ids", { + ped <- make_pedigree() + ped$id[2] <- ped$id[1] + expect_error(common.shared(ped), "All id values must be unique") +}) + +test_that("common.shared() gives a block-diagonal sparse Matrix for a pedigreeList", { + result <- common.shared(make_two_families()) + + expect_s4_class(result, "Matrix") + ids <- as.character(c(1:4, 11:14)) + expected <- kronecker(diag(2), matrix(1, 4, 4)) + dimnames(expected) <- list(ids, ids) + expect_equal(as.matrix(result), expected) +}) + +test_that("common.shared() prefixes famid when ids repeat across families", { + result <- common.shared(make_two_families(id = c(1:4, 1:4))) + expect_equal(colnames(result), paste(rep(c("A", "B"), each = 4), 1:4, sep = "/")) +}) diff --git a/tests/testthat/test-drop1.geeglm.R b/tests/testthat/test-drop1.geeglm.R new file mode 100644 index 0000000..bfa42fd --- /dev/null +++ b/tests/testthat/test-drop1.geeglm.R @@ -0,0 +1,76 @@ +wald <- function(beta, vcov) drop(t(beta) %*% solve(vcov) %*% beta) + +test_that("drop1() on geeglm gives Wald tests per term", { + fit <- fit_warpbreaks_geeglm() + out <- drop1(fit) + b <- coef(fit) + V <- fit$geese$vbeta + + expect_s3_class(out, c("anova", "data.frame")) + expect_named(out, c("DF", "Wald", "Pr(>Chi)")) + expect_equal(rownames(out), c("wool", "tension")) + expect_equal(out$DF, c(1, 2)) + # 1 df term: same as the coefficient Wald test reported by geepack + expect_equal(out["wool", "Wald"], summary(fit)$coefficients["woolB", "Wald"]) + # 2 df term: quadratic form of the two tension coefficients + expect_equal(out["tension", "Wald"], wald(b[3:4], V[3:4, 3:4])) + expect_equal(out[["Pr(>Chi)"]], pchisq(out$Wald, out$DF, lower.tail = FALSE)) +}) + +test_that("drop1() on geeglm agrees with geepack's anova() for the last term", { + withr::local_package("geepack") + fit <- fit_warpbreaks_geeglm() + expect_equal(drop1(fit)["tension", "Wald"], anova(fit)["tension", "X2"]) +}) + +test_that("drop1() on geeglm uses the naive variance with method = 'naive'", { + fit <- fit_warpbreaks_geeglm() + b <- coef(fit) + V <- fit$geese$vbeta.naiv + + out <- drop1(fit, method = "naive") + expect_equal(out$Wald, c(wald(b[2], V[2, 2]), wald(b[3:4], V[3:4, 3:4]))) + expect_equal(drop1(fit, method = "sandwich"), drop1(fit, method = "robust")) +}) + +test_that("drop1() on geeglm restricts terms with scope", { + fit <- fit_warpbreaks_geeglm() + full <- drop1(fit) + + expect_equal(drop1(fit, scope = ~tension)$Wald, full["tension", "Wald"]) + expect_equal(drop1(fit, scope = "wool")$Wald, full["wool", "Wald"]) + expect_error(drop1(fit, scope = ~foo), "scope is not a subset of term labels") +}) + +test_that("drop1() on geeglm computes score tests", { + fit <- fit_warpbreaks_geeglm() + + score <- drop1(fit, test = "score") + expect_named(score, c("DF", "Score", "Pr(>Chi)")) + expect_equal(score$Score, c(3.774668117, 10.086491034), tolerance = 1e-6) # regression values + expect_equal(score[["Pr(>Chi)"]], pchisq(score$Score, c(1, 2), lower.tail = FALSE)) + + sas <- drop1(fit, test = "sasscore") + expect_named(sas, c("DF", "Score(SAS)", "Pr(>Chi)")) + expect_equal(sas[["Score(SAS)"]], c(3.177161756, 7.627752460), tolerance = 1e-6) # regression values +}) + +test_that("drop1() on geem gives the same Wald tests as on geeglm", { + g <- geeM::geem( + breaks ~ wool + tension, id = rep(1:18, each = 3), data = warpbreaks, + family = "poisson", corstr = "exchangeable" + ) + out <- drop1(g) + + expect_named(out, c("DF", "Wald", "Pr(>Chi)")) + expect_equal(out["wool", "Wald"], summary(g)$wald.test[2]^2) + expect_equal(out["tension", "Wald"], wald(g$beta[3:4], g$var[3:4, 3:4])) + expect_equal(drop1(g, method = "naive")$Wald[1], g$beta[2]^2 / g$naiv.var[2, 2]) + expect_equal(out$Wald, drop1(fit_warpbreaks_geeglm())$Wald, tolerance = 1e-4) +}) + +test_that("model.matrix() on geem returns the design matrix", { + g <- geeM::geem(breaks ~ wool + tension, id = rep(1:18, each = 3), data = warpbreaks, family = "poisson") + expect_identical(model.matrix(g), g$X) + expect_equal(unname(model.matrix(g)), unname(model.matrix(~ wool + tension, warpbreaks)), ignore_attr = TRUE) +}) diff --git a/tests/testthat/test-expand.R b/tests/testthat/test-expand.R new file mode 100644 index 0000000..da4a9e1 --- /dev/null +++ b/tests/testthat/test-expand.R @@ -0,0 +1,29 @@ +test_that("expand_table() expands a matrix to one row per count", { + m <- matrix(c(2, 1, 3, 0, 0, 2), 3) + result <- expand_table(m) + + expect_named(result, c("Var1", "Var2")) + expect_equal(nrow(result), sum(m)) + # Tabulating the expanded data recovers the original counts + expect_equal(unclass(table(result)), m, ignore_attr = TRUE) +}) + +test_that("expand_table() keeps dimnames of a 2-way table", { + x <- as.table(matrix(1:4, 2, dimnames = list(a = c("x", "y"), b = c("u", "v")))) + result <- expand_table(x) + + expect_named(result, c("a", "b")) + expect_equal(table(result), x, ignore_attr = "class") +}) + +test_that("expand_table() handles a 3-way table", { + result <- expand_table(UCBAdmissions) + + expect_named(result, c("Admit", "Gender", "Dept")) + expect_equal(nrow(result), sum(UCBAdmissions)) + expect_equal(table(result), UCBAdmissions, ignore_attr = "class") +}) + +test_that("expand_table() errors for non-matrix, non-table input", { + expect_error(expand_table(1:5), "needs matrix or table as input") +}) diff --git a/tests/testthat/test-extended.shared.R b/tests/testthat/test-extended.shared.R new file mode 100644 index 0000000..bf242da --- /dev/null +++ b/tests/testthat/test-extended.shared.R @@ -0,0 +1,51 @@ +# Nuclear family: father 1, mother 2, children 3 and 4 +make_nuclear_family <- function() { + kinship2::pedigree(1:4, c(0, 0, 1, 1), c(0, 0, 2, 2), c(1, 2, 1, 2)) +} + +test_that("extended.shared() matches the closed form for a nuclear family", { + ped <- make_nuclear_family() + + expect_equal(extended.shared(ped), nuclear_expected(rho = 1, theta = 1)) + expect_equal(extended.shared(ped, rho = 0.5, theta = 0.5), nuclear_expected(0.5, 0.5)) + expect_equal(extended.shared(ped, rho = 0, theta = 1), nuclear_expected(0, 1)) +}) + +test_that("extended.shared() returns a symmetric matrix for the 14-person pedigree", { + result <- extended.shared(make_pedigree()) + + expect_equal(dim(result), c(14, 14)) + expect_equal(dimnames(result), list(as.character(1:14), as.character(1:14))) + expect_true(isSymmetric(result)) + # Individuals with two founder parents have variance 1. Individual 9 has a + # founder father (3) and a non-founder mother (6) that are uncorrelated, so + # the variance is 2 * (1/2)^2 = 0.5 (likewise 10). Individual 14 has + # uncorrelated parents with variances 0.5 and 1: (0.5 + 1) / 4 = 0.375. + expect_equal(unname(diag(result)), c(rep(1, 8), 0.5, 0.5, 1, 1, 1, 0.375)) +}) + +test_that("extended.shared() handles a single-person pedigree", { + one <- kinship2::pedigree(1, NA, NA, "male") + expect_identical(extended.shared(one), matrix(1, 1, 1, dimnames = list("1", "1"))) +}) + +test_that("extended.shared() errors on duplicated ids", { + ped <- make_pedigree() + ped$id[2] <- ped$id[1] + expect_error(extended.shared(ped), "All id values must be unique") +}) + +test_that("extended.shared() gives a block-diagonal sparse Matrix for a pedigreeList", { + result <- extended.shared(make_two_families()) + + expect_s4_class(result, "Matrix") + expected <- as.matrix(Matrix::bdiag(nuclear_expected(1, 1), nuclear_expected(1, 1))) + ids <- as.character(c(1:4, 11:14)) + dimnames(expected) <- list(ids, ids) + expect_equal(as.matrix(result), expected) +}) + +test_that("extended.shared() prefixes famid when ids repeat across families", { + result <- extended.shared(make_two_families(id = c(1:4, 1:4))) + expect_equal(colnames(result), paste(rep(c("A", "B"), each = 4), 1:4, sep = "/")) +}) diff --git a/tests/testthat/test-fac2num.R b/tests/testthat/test-fac2num.R new file mode 100644 index 0000000..44178e6 --- /dev/null +++ b/tests/testthat/test-fac2num.R @@ -0,0 +1,16 @@ +test_that("fac2num() returns the numeric value of the levels, not the codes", { + f <- factor(c(10, 2, 0.5, 2)) + # as.numeric(f) would return the internal codes c(3, 2, 1, 2) + expect_equal(fac2num(f), c(10, 2, 0.5, 2)) +}) + +test_that("fac2num() returns NA with a warning for non-numeric levels", { + f <- factor(c("a", "1", "2")) + expect_warning(res <- fac2num(f), class = "warning") + expect_equal(res, c(NA, 1, 2)) +}) + +test_that("fac2num() errors for non-factor input", { + expect_error(fac2num(c(1, 2, 3)), "input needs to be a factor") + expect_error(fac2num("abc"), "input needs to be a factor") +}) diff --git a/tests/testthat/test-feature.test.R b/tests/testthat/test-feature.test.R new file mode 100644 index 0000000..9298b89 --- /dev/null +++ b/tests/testthat/test-feature.test.R @@ -0,0 +1,15 @@ +test_that("feature.test returns NA p-values when lambda selects no variables", { + d <- make_feature_data() + withr::local_options(warn = 0) + + res <- feature.test(d$x, d$y, B = 5, s = 10, control = list(maxcores = 1)) + + expect_named(res, c("p.full", "ols.selected", "p.maxols", "lasso.selected", + "p.maxlasso", "lambda.orig", "B")) + expect_identical(res$p.full, NA) + expect_identical(res$p.maxols, NA) + expect_identical(res$p.maxlasso, NA) + expect_identical(res$lambda.orig, 10) + expect_identical(res$B, 5) + expect_equal(getOption("warn"), 0) +}) diff --git a/tests/testthat/test-fitted.geese.R b/tests/testthat/test-fitted.geese.R new file mode 100644 index 0000000..c66a06a --- /dev/null +++ b/tests/testthat/test-fitted.geese.R @@ -0,0 +1,15 @@ +test_that("fitted.geese returns fitted values for a binomial geese fit", { + dat <- make_gee_data() + fit <- geepack::geese(y ~ x1 + age, id = id, data = dat, corstr = "exchangeable", family = binomial()) + ref <- geepack::geeglm(y ~ x1 + age, id = id, data = dat, corstr = "exchangeable", family = binomial()) + + expect_equal(as.vector(fitted(fit)), as.vector(fitted(ref))) +}) + +test_that("fitted.geese returns fitted values for a gaussian geese fit", { + dat <- make_gee_data() + fit <- geepack::geese(x1 ~ age, id = id, data = dat, corstr = "exchangeable", family = gaussian()) + ref <- geepack::geeglm(x1 ~ age, id = id, data = dat, corstr = "exchangeable", family = gaussian()) + + expect_equal(as.vector(fitted(fit)), as.vector(fitted(ref))) +}) diff --git a/tests/testthat/test-founder.env.R b/tests/testthat/test-founder.env.R new file mode 100644 index 0000000..498c4be --- /dev/null +++ b/tests/testthat/test-founder.env.R @@ -0,0 +1,57 @@ +test_that("founder.shared.pedigree marks each individual and each mating pair", { + ped <- make_pedigree() + + # Mating pairs (dad, mom) in make_pedigree(): 1x2, 3x4, 3x6, 7x2, 11x12, 10x13 + expected <- diag(14) + pairs <- rbind(c(1, 2), c(3, 4), c(3, 6), c(7, 2), c(11, 12), c(10, 13)) + expected[pairs] <- 1 + expected[pairs[, 2:1]] <- 1 + dimnames(expected) <- list(as.character(1:14), as.character(1:14)) + + expect_identical(founder.shared(ped), expected) +}) + +test_that("founder.shared.pedigree handles a single-person pedigree", { + one <- kinship2::pedigree(id = 1, dadid = NA, momid = NA, sex = "male") + expect_identical(founder.shared(one), matrix(1, 1, 1, dimnames = list("1", "1"))) +}) + +test_that("founder.shared.pedigree errors on duplicated ids", { + ped <- make_pedigree() + ped$id[2] <- ped$id[1] + expect_error(founder.shared(ped), "All id values must be unique") +}) + +test_that("founder.shared.pedigreeList returns a block-diagonal sparse matrix", { + fam <- data.frame( + id = c(1, 2, 3, 11, 12, 13), + dadid = c(NA, NA, 1, NA, NA, 11), + momid = c(NA, NA, 2, NA, NA, 12), + sex = c("male", "female", "male", "male", "female", "male"), + famid = c("A", "A", "A", "B", "B", "B") + ) + pedlist <- with(fam, kinship2::pedigree(id, dadid, momid, sex, famid = famid)) + + res <- founder.shared(pedlist) + expect_s4_class(res, "Matrix") + + # Founders 1x2 (family A) and 11x12 (family B) are mating pairs + block <- matrix(c(1, 1, 0, 1, 1, 0, 0, 0, 1), 3) + expected <- as.matrix(Matrix::bdiag(block, block)) + dimnames(expected) <- list(as.character(fam$id), as.character(fam$id)) + expect_equal(as.matrix(res), expected) +}) + +test_that("founder.shared.pedigreeList uses famid/id names when ids repeat across families", { + fam <- data.frame( + id = c(1, 2, 3, 1, 2, 3), + dadid = c(NA, NA, 1, NA, NA, 1), + momid = c(NA, NA, 2, NA, NA, 2), + sex = c("male", "female", "male", "male", "female", "male"), + famid = c("A", "A", "A", "B", "B", "B") + ) + pedlist <- with(fam, kinship2::pedigree(id, dadid, momid, sex, famid = famid)) + + res <- founder.shared(pedlist) + expect_identical(colnames(res), c("A/1", "A/2", "A/3", "B/1", "B/2", "B/3")) +}) diff --git a/tests/testthat/test-geekin.R b/tests/testthat/test-geekin.R new file mode 100644 index 0000000..e55c932 --- /dev/null +++ b/tests/testthat/test-geekin.R @@ -0,0 +1,64 @@ +test_that("geekin with a block-of-ones varlist equals an exchangeable geeglm fit", { + dat <- make_gee_data() + V <- exchangeable_varlist() + + fit <- geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = list(V)) + ref <- geepack::geeglm(y ~ x1 + age, id = id, data = dat, family = binomial, corstr = "exchangeable") + + expect_s3_class(fit, c("geekin", "geeglm")) + expect_equal(coef(fit), coef(ref)) + expect_equal(unname(fit$geese$alpha), unname(ref$geese$alpha)) + expect_identical(fit$geese$model$corstr, "userdefined") +}) + +test_that("geekin accepts a single matrix as varlist", { + dat <- make_gee_data() + V <- exchangeable_varlist() + + fit_list <- geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = list(V)) + fit_matrix <- geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = V) + expect_equal(coef(fit_matrix), coef(fit_list)) +}) + +test_that("geekin drops observations with missing values like geeglm", { + dat <- make_gee_data() + dat$x1[c(3, 10)] <- NA + V <- exchangeable_varlist() + + fit <- geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = list(V)) + ref <- geepack::geeglm(y ~ x1 + age, id = id, data = na.omit(dat), family = binomial, + corstr = "exchangeable") + + expect_equal(coef(fit), coef(ref)) + expect_identical(as.vector(fit$na.action), c(3L, 10L)) +}) + +test_that("geekin validates varlist and cluster ordering", { + dat <- make_gee_data() + V <- exchangeable_varlist() + + expect_error( + geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = "V"), + "varlist must be a list" + ) + + shuffled <- dat[order(dat$age), ] + expect_error( + geekin(y ~ x1 + age, id = shuffled$id, data = shuffled, family = binomial, varlist = list(V)), + "contiguous blocks" + ) +}) + +test_that("print.geekin shows the call, coefficients and correlation parameters", { + dat <- make_gee_data() + V <- exchangeable_varlist() + fit <- geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = list(V)) + + out <- capture.output(res <- print(fit)) + expect_identical(res, fit) + expect_true("Call:" %in% out) + expect_true("Coefficients:" %in% out) + expect_true("Estimated Correlation Parameters:" %in% out) + expect_match(out, "Degrees of Freedom: 80 Total", fixed = TRUE, all = FALSE) + expect_match(out, "Number of clusters: 20 Maximum cluster size: 4", fixed = TRUE, all = FALSE) +}) diff --git a/tests/testthat/test-gkgamma.R b/tests/testthat/test-gkgamma.R new file mode 100644 index 0000000..e79bea4 --- /dev/null +++ b/tests/testthat/test-gkgamma.R @@ -0,0 +1,43 @@ +test_that("gkgamma equals Yule's Q for a 2x2 table", { + tab <- matrix(c(10, 5, 3, 12), nrow = 2) + # Yule's Q = (ad - bc) / (ad + bc) = (120 - 15) / (120 + 15) + expect_equal(unname(gkgamma(tab)$estimate), 105 / 135) +}) + +test_that("gkgamma gives +1 / -1 for perfectly concordant / discordant tables", { + expect_equal(unname(gkgamma(diag(c(5, 5, 5)))$estimate), 1) + expect_equal(unname(gkgamma(diag(c(5, 5, 5))[, 3:1])$estimate), -1) +}) + +test_that("gkgamma reproduces the documented smoking example", { + smoke <- matrix( + c(16, 15, 13, 10, 1, 73, 75, 59, 81, 29, 6, 6, 7, 17, 3, 1, 0, 1, 3, 1), + ncol = 4 + ) + res <- gkgamma(smoke) + + expect_s3_class(res, "htest") + expect_equal(unname(res$estimate), 0.2418173666, tolerance = 1e-8) + expect_equal(res$se0, 0.07334398549, tolerance = 1e-8) + expect_equal(res$se1, 0.07066251422, tolerance = 1e-8) + expect_equal(unname(res$statistic), 3.297030629, tolerance = 1e-8) + expect_equal(res$data.name, "smoke") + expect_identical(res$observed, smoke) +}) + +test_that("gkgamma p-value and confidence interval follow from estimate and SEs", { + smoke <- matrix( + c(16, 15, 13, 10, 1, 73, 75, 59, 81, 29, 6, 6, 7, 17, 3, 1, 0, 1, 3, 1), + ncol = 4 + ) + res <- gkgamma(smoke, conf.level = 0.90) + est <- unname(res$estimate) + + expect_equal(unname(res$statistic), est / res$se0) + expect_equal(res$p.value, 2 * pnorm(-abs(est / res$se0))) + expect_equal( + as.vector(res$conf.int), + est + c(-1, 1) * qnorm(0.95) * res$se1 + ) + expect_identical(attr(res$conf.int, "conf.level"), 0.90) +}) diff --git a/tests/testthat/test-ht.R b/tests/testthat/test-ht.R new file mode 100644 index 0000000..7b5c907 --- /dev/null +++ b/tests/testthat/test-ht.R @@ -0,0 +1,32 @@ +test_that("ht prints head and tail separated by an ellipsis", { + expect_output( + ht(1:20), + "[1] 1 2 3 4 5 6\n...\n[1] 15 16 17 18 19 20", + fixed = TRUE + ) +}) + +test_that("ht: n and m control the number of head and tail elements", { + expect_identical( + capture.output(ht(1:20, n = 2, m = 3)), + c("[1] 1 2", "...", "[1] 18 19 20") + ) +}) + +test_that("ht returns NULL invisibly when printing", { + capture.output(vis <- withVisible(ht(1:20))) + expect_null(vis$value) + expect_false(vis$visible) +}) + +test_that("ht with returnList = TRUE returns head and tail without printing", { + expect_silent(res <- ht(1:20, returnList = TRUE)) + expect_identical(res, list(head = 1:6, tail = 15:20)) +}) + +test_that("ht works on data frames", { + df <- data.frame(a = 1:10, b = letters[1:10]) + res <- ht(df, n = 2, m = 1, returnList = TRUE) + expect_identical(res$head, df[1:2, ]) + expect_identical(res$tail, df[10, ]) +}) diff --git a/tests/testthat/test-known-bugs.R b/tests/testthat/test-known-bugs.R new file mode 100644 index 0000000..8a3b551 --- /dev/null +++ b/tests/testthat/test-known-bugs.R @@ -0,0 +1,234 @@ +skip("Known bugs documented in this file") +# Tests documenting confirmed defects in the package source. +# +# Every test here starts with # behaviour. When a defect is fixed upstream, delete the skip line and move the +# test back to the test file for that function (the section headers below). +# See tests/testthat/KNOWN_BUGS.md for details on each defect. + +# test-drop1.geeglm.R --------------------------------------------------------- + +test_that("drop1() score tests work when the data is a local variable", { + local_data <- warpbreaks + fit <- geepack::geeglm(breaks ~ wool + tension, id = rep(1:18, each = 3), data = local_data, family = poisson) + expect_named(drop1(fit, test = "score"), c("DF", "Score", "Pr(>Chi)")) +}) + +test_that("drop1() on geeglm with test = 'none' keeps the statistic", { + out <- drop1(fit_warpbreaks_geeglm(), test = "none") + expect_named(out, c("DF", "Wald")) +}) + +test_that("drop1() on geem computes score tests", { + g <- geeM::geem(breaks ~ wool + tension, id = rep(1:18, each = 3), data = warpbreaks, family = "poisson") + expect_named(drop1(g, test = "score"), c("DF", "Score", "Pr(>Chi)")) +}) + +test_that("drop1() on geese gives Wald tests per term", { + gs <- geepack::geese( + breaks ~ wool + tension, id = rep(1:18, each = 3), data = warpbreaks, + family = poisson, corstr = "exchangeable" + ) + expect_equal(drop1(gs)$Wald, drop1(fit_warpbreaks_geeglm())$Wald) +}) + +# test-extended.shared.R ------------------------------------------------------ + +test_that("extended.shared() handles a pedigree with a single non-founder", { + trio <- kinship2::pedigree(1:3, c(0, 0, 1), c(0, 0, 2), c(1, 2, 1)) + expect_equal(extended.shared(trio), nuclear_expected(1, 1)[1:3, 1:3]) +}) + +test_that("extended.shared() passes rho and theta on for a pedigreeList", { + result <- extended.shared(make_two_families(), rho = 0.5, theta = 0.5) + expect_equal(as.matrix(result)[1:4, 1:4], nuclear_expected(0.5, 0.5), ignore_attr = TRUE) +}) + +# test-feature.test.R --------------------------------------------------------- + +test_that("feature.test selects the true predictor and returns permutation p-values", { + d <- make_feature_data() + withr::local_seed(1) + + capture.output(res <- feature.test(d$x, d$y, B = 5, s = 0.2, control = list(maxcores = 1))) + + expect_identical(res$lasso.selected[1], 1L) + expect_identical(res$ols.selected[1], 1L) + expect_true(all(c(res$p.full, res$p.maxols, res$p.maxlasso) >= 0)) + expect_true(all(c(res$p.full, res$p.maxols, res$p.maxlasso) <= 1)) +}) + +# test-geekin.R --------------------------------------------------------------- + +test_that("print.geekin does not change the global digits option", { + dat <- make_gee_data() + V <- exchangeable_varlist() + fit <- geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = list(V)) + + withr::local_options(digits = 7) + capture.output(print(fit, digits = 3)) + expect_identical(getOption("digits"), 7L) +}) + +test_that("geekin works when geepack is not attached", { + env <- new.env(parent = globalenv()) + env$dat <- make_gee_data() + env$V <- exchangeable_varlist() + + expect_no_error(evalq( + MESS::geekin(y ~ x1 + age, id = dat$id, data = dat, family = binomial, varlist = list(V)), + env + )) +}) + +# test-loadRData.R ------------------------------------------------------------ + +test_that("loadRData returns an object that is named 'filename'", { + path <- withr::local_tempfile(fileext = ".RData") + filename <- 1:3 + save(filename, file = path) + + expect_identical(loadRData(path), 1:3) +}) + +# test-lower.tri.vector.R ----------------------------------------------------- + +test_that("lower.tri.vector rejects a non-square matrix", { + expect_error(lower.tri.vector(matrix(1:12, nrow = 3)), "square matrix") +}) + +# test-panel.R ---------------------------------------------------------------- + +test_that("panel.hist and panel.r2 restore par('usr') without warnings", { + withr::local_pdf(NULL) + x <- c(1, 3, 2, 5, 4, 6, 8, 7, 9) + + plot.new() + plot.window(xlim = c(0, 10), ylim = c(0, 10)) + usr <- par("usr") + expect_no_warning(panel.hist(x)) + expect_equal(par("usr"), usr) + expect_no_warning(panel.r2(x, rev(x))) + expect_equal(par("usr"), usr) +}) + +# test-power.binom.test.R ----------------------------------------------------- + +test_that("power_binom_test two-sided test keeps its level for symmetric p0", { + expect_lte(power_binom_test(n = 50, p0 = 0.5, pa = 0.5)$power, 0.05) + expect_equal(power_binom_test(n = 50, p0 = 0.5, pa = 0.75)$power, binom_test_power(50, 0.5, 0.75)) +}) + +test_that("power_binom_test solves for p0", { + res <- power_binom_test(n = 50, pa = 0.45, power = 0.8, alternative = "greater") + expect_equal( + power_binom_test(n = 50, p0 = res$p0, pa = 0.45, alternative = "greater")$power, + 0.8, + tolerance = 1e-3 + ) +}) + +# test-power.mcnemar.test.R --------------------------------------------------- + +test_that("power_mcnemar_test accepts psi = 1 as its error message states", { + # With no effect, two-sided normal-approximation power is sig.level / 2 + expect_equal(power_mcnemar_test(n = 60, paid = 0.1, psi = 1)$power, 0.025) +}) + +# test-power.prop.test.R ------------------------------------------------------ + +test_that("power_prop_test one-sided power matches stats::power.prop.test", { + expect_equal(power_prop_test(n = 50, p1 = 0.5, p2 = 0.5, alternative = "one.sided")$power, 0.05) + expect_equal( + power_prop_test(n = 50, p1 = 0.5, p2 = 0.7, alternative = "one.sided")$power, + power.prop.test(n = 50, p1 = 0.5, p2 = 0.7, alternative = "one.sided")$power + ) +}) + +test_that("power_prop_test solves for sig.level", { + res <- power_prop_test(n = 93, p1 = 0.5, p2 = 0.7, power = 0.8, sig.level = NULL) + expect_equal( + res$sig.level, + power.prop.test(n = 93, p1 = 0.5, p2 = 0.7, power = 0.8, sig.level = NULL)$sig.level, + tolerance = 1e-3 + ) +}) + +# test-prepost.R -------------------------------------------------------------- + +test_that("missing post values are handled with the semiparametric estimator", { + # Example data from the documentation (Altman) + expo <- c(rep(1, 9), rep(0, 7)) + bp_base <- c(147, 129, 158, 164, 134, 155, 151, 141, 153, 133, 129, 152, 161, 154, 141, 156) + post <- c(137, 120, 141, 137, 140, 144, 134, 123, 142, 139, 134, 136, 151, 147, 137, 149) + post[c(2, 10, 12)] <- NA + + res <- prepost.test(bp_base, post, expo) + # Reference value computed with the Davidian, Tsiatis & Leon (2005) + # estimator using the control-arm regression in the control augmentation term. + expect_equal(unname(res$estimate), -6.640460422, tolerance = 1e-8) +}) + +# test-qic.R ------------------------------------------------------------------ + +test_that("QIC works when the model data is a local variable", { + dat <- geepack::ohio + fit <- geepack::geeglm(resp ~ age + smoke, id = id, data = dat, + family = binomial, corstr = "exchangeable") + expect_equal(MESS::QIC(fit), geepack::QIC(fit)) +}) + +test_that("models can be compared by passing them positionally", { + fit1 <- geepack::geeglm(resp ~ age + smoke, id = id, data = geepack::ohio, family = binomial) + fit2 <- geepack::geeglm(resp ~ age, id = id, data = geepack::ohio, family = binomial) + + res <- MESS::QIC(fit1, fit2) + expect_equal(dim(res), c(2, 6)) +}) + +test_that("QIC works for an ordgee fit", { + fit <- geepack::ordgee(ordered(resp) ~ age, id = id, data = geepack::ohio) + expect_named(MESS::QIC(fit), c("QIC", "QICu", "Quasi Lik", "CIC", "params", "QICC")) +}) + +# test-RcppExports-stats.R ---------------------------------------------------- + +test_that("cumsumbinning() numbers groups from 1 when the first value exceeds the threshold", { + expect_equal(cumsumbinning(c(15, 1, 2), 10), c(1, 2, 2)) +}) + +test_that("ks_cumtest() rescales prob to sum to 1", { + withr::local_seed(1) + res <- ks_cumtest(1:6, B = 100, prob = c(5, 1, 1, 1, 1, 1)) + expect_equal(unname(res$statistic), 6 / 10 - 3 / 21) +}) + +test_that("maximum_subarray() rejects an empty vector", { + expect_error(maximum_subarray(numeric(0))) +}) + +# test-rnormperfect.R --------------------------------------------------------- + +test_that("the sample is centred at mean and scaled by sd", { + res <- rnorm_perfect(30, mean = 10, sd = 2) + expect_equal(mean(res), 10) + expect_equal(res, 10 + 2 * qnorm((1:30) / 31)) +}) + +# test-screener.R ------------------------------------------------------------- + +test_that("selected is a list even when every lambda selects the same number of variables", { + res <- screen_variables(diag(3), c(3, 2, 1), lambda = c(2.4, 2.5)) + expect_equal(res$selected, list(3L, 3L)) +}) + +test_that("global-DPP method applies the DPP criterion", { + x <- diag(3) + y <- c(3, 2, 1) + lambda <- 2.5 + # criterion = lambdamax - ||x||_2 * ||y||_2 * (lambdamax - lambda) / lambda + criterion <- 3 - 1 * sqrt(14) * 0.5 / 2.5 + + res <- screen_variables(x, y, lambda = lambda, method = "global-DPP") + expect_equal(res$method, "global-DPP") + expect_equal(res$selected, list(which(c(3, 2, 1) < criterion))) +}) diff --git a/tests/testthat/test-loadRData.R b/tests/testthat/test-loadRData.R new file mode 100644 index 0000000..e1e6e13 --- /dev/null +++ b/tests/testthat/test-loadRData.R @@ -0,0 +1,7 @@ +test_that("loadRData returns the saved object regardless of its name", { + path <- withr::local_tempfile(fileext = ".RData") + my_object <- data.frame(x = 1:3, y = letters[1:3]) + save(my_object, file = path) + + expect_identical(loadRData(path), my_object) +}) diff --git a/tests/testthat/test-lower.tri.vector.R b/tests/testthat/test-lower.tri.vector.R new file mode 100644 index 0000000..7c0fe06 --- /dev/null +++ b/tests/testthat/test-lower.tri.vector.R @@ -0,0 +1,30 @@ +test_that("lower.tri.vector without clusters equals m[lower.tri(m)]", { + m <- matrix(1:16, ncol = 4) + expect_identical(lower.tri.vector(m), m[lower.tri(m)]) + expect_identical(lower.tri.vector(m, diag = TRUE), m[lower.tri(m, diag = TRUE)]) +}) + +test_that("lower.tri.vector extracts within-cluster blocks (documented example)", { + m <- matrix(1:64, ncol = 8) + cluster <- c(1, 1, 1, 1, 2, 2, 3, 3) + # Block 1 = rows/cols 1:4, block 2 = 5:6, block 3 = 7:8 + expect_equal(lower.tri.vector(m, cluster), c(2, 3, 4, 11, 12, 20, 38, 56)) + expect_equal( + lower.tri.vector(m, cluster, diag = TRUE), + c(1, 2, 3, 4, 10, 11, 12, 19, 20, 28, 37, 38, 46, 55, 56, 64) + ) +}) + +test_that("lower.tri.vector works on sparse Matrix objects", { + m <- matrix(1:16, ncol = 4) + expect_equal(lower.tri.vector(Matrix::Matrix(m)), m[lower.tri(m)]) +}) + +test_that("lower.tri.vector validates the cluster argument", { + m <- matrix(1:64, ncol = 8) + expect_error(lower.tri.vector(m, c(1, 1)), "Length of cluster vector must match") + expect_error( + lower.tri.vector(m, cluster = c(2, 1, 1, 1, 1, 1, 2, 2)), + "contiguous blocks" + ) +}) diff --git a/tests/testthat/test-onemargintest.R b/tests/testthat/test-onemargintest.R new file mode 100644 index 0000000..ec66e31 --- /dev/null +++ b/tests/testthat/test-onemargintest.R @@ -0,0 +1,3 @@ +test_that("expect deprecated warning", { + expect_warning(onemargintest(), "deprecated") +}) diff --git a/tests/testthat/test-orcor.R b/tests/testthat/test-orcor.R new file mode 100644 index 0000000..6de2736 --- /dev/null +++ b/tests/testthat/test-orcor.R @@ -0,0 +1,24 @@ +test_that("orcor() default type gives known odds ratios", { + # OR = (1 + rho) / (1 - rho) + expect_equal(orcor(0), 1) + expect_equal(orcor(0.5), 3) + expect_equal(orcor(-0.5), 1 / 3) + expect_equal(orcor(1), Inf) + expect_equal(orcor(-1), 0) +}) + +test_that("orcor() is vectorised over rho", { + expect_equal(orcor(c(0, 0.5, -0.5)), c(1, 3, 1 / 3)) +}) + +test_that("orcor() youden type gives known odds ratios", { + # l = 2 * asin(rho) / pi; rho = sin(pi / 4) gives l = 0.5, so OR = (1.5 / 0.5)^2 = 9 + expect_equal(orcor(0, type = "youden"), 1) + expect_equal(orcor(sin(pi / 4), type = "youden"), 9) + expect_equal(orcor(-sin(pi / 4), type = "youden"), 1 / 9) + expect_equal(orcor(1, type = "youden"), Inf) +}) + +test_that("orcor() youden type ignores lambda", { + expect_equal(orcor(0.3, type = "youden", lambda = 3), orcor(0.3, type = "youden", lambda = 0)) +}) diff --git a/tests/testthat/test-ordered.clusters.R b/tests/testthat/test-ordered.clusters.R new file mode 100644 index 0000000..986db23 --- /dev/null +++ b/tests/testthat/test-ordered.clusters.R @@ -0,0 +1,17 @@ +test_that("ordered.clusters is TRUE when equal ids are contiguous", { + expect_true(ordered.clusters(c(1, 1, 1, 2, 2, 3))) + expect_true(ordered.clusters(c(3, 3, 1, 2, 2))) + expect_true(ordered.clusters(c("a", "a", "b"))) + expect_true(ordered.clusters(factor(c("b", "b", "a")))) +}) + +test_that("ordered.clusters is FALSE when an id reappears later", { + expect_false(ordered.clusters(c(1, 2, 1))) + expect_false(ordered.clusters(c(1, 1, 1, 2, 2, 3, 4, 1, 5, 5, 5))) +}) + +test_that("ordered.clusters is TRUE for vectors without duplicates", { + expect_true(ordered.clusters(c(1, 2, 3))) + expect_true(ordered.clusters(1)) + expect_true(ordered.clusters(numeric(0))) +}) diff --git a/tests/testthat/test-pairwise.cor.test.R b/tests/testthat/test-pairwise.cor.test.R new file mode 100644 index 0000000..520ef44 --- /dev/null +++ b/tests/testthat/test-pairwise.cor.test.R @@ -0,0 +1,64 @@ +make_grouped_data <- function() { + withr::local_seed(42) + data.frame(x = rnorm(30), g = factor(rep(c("A", "B", "C"), each = 10))) +} + +test_that("pairwise.cor.test p-values equal adjusted cor.test p-values", { + d <- make_grouped_data() + xa <- d$x[d$g == "A"] + xb <- d$x[d$g == "B"] + xc <- d$x[d$g == "C"] + raw <- c(cor.test(xb, xa)$p.value, cor.test(xc, xa)$p.value, cor.test(xc, xb)$p.value) + + res <- pairwise.cor.test(d$x, d$g) + expect_s3_class(res, "pairwise.htest") + expect_identical(res$p.adjust.method, "holm") + expect_identical(res$method, "Pearson's product-moment correlation") + expect_identical(res$data.name, "d$x and d$g") + + adjusted <- p.adjust(raw, "holm") + expect_equal(res$p.value["B", "A"], adjusted[1]) + expect_equal(res$p.value["C", "A"], adjusted[2]) + expect_equal(res$p.value["C", "B"], adjusted[3]) + expect_identical(res$p.value["B", "B"], NA_real_) +}) + +test_that("pairwise.cor.test honours p.adjust.method", { + d <- make_grouped_data() + raw <- pairwise.cor.test(d$x, d$g, p.adjust.method = "none")$p.value + bonf <- pairwise.cor.test(d$x, d$g, p.adjust.method = "bonferroni") + + expect_identical(bonf$p.adjust.method, "bonferroni") + expect_equal(bonf$p.value, pmin(3 * raw, 1)) +}) + +test_that("pairwise.cor.test supports kendall and spearman and passes ... to cor.test", { + d <- make_grouped_data() + xa <- d$x[d$g == "A"] + xb <- d$x[d$g == "B"] + + kendall <- pairwise.cor.test(d$x, d$g, method = "kendall", p.adjust.method = "none") + expect_identical(kendall$method, "Kendall's rank correlation tau") + expect_equal(kendall$p.value["B", "A"], cor.test(xb, xa, method = "kendall")$p.value) + + spearman <- pairwise.cor.test(d$x, d$g, method = "spearman", p.adjust.method = "none") + expect_identical(spearman$method, "Spearman's rank correlation rho") + expect_equal(spearman$p.value["B", "A"], cor.test(xb, xa, method = "spearman")$p.value) + + greater <- pairwise.cor.test(d$x, d$g, p.adjust.method = "none", alternative = "greater") + expect_equal(greater$p.value["B", "A"], cor.test(xb, xa, alternative = "greater")$p.value) +}) + +test_that("pairwise.cor.test returns NA with a warning for unequal group sizes", { + x <- c(1, 2, 3, 4, 5, 2, 4, 6, 8, 10, 12, 14) + g <- rep(c("A", "B"), c(5, 7)) + + expect_warning(res <- pairwise.cor.test(x, g), "Group sizes are not identical") + expect_identical(res$p.value["B", "A"], NA_real_) +}) + +test_that("pairwise.cor.test rejects unknown method arguments", { + d <- make_grouped_data() + expect_error(pairwise.cor.test(d$x, d$g, method = "nope"), "should be one of") + expect_error(pairwise.cor.test(d$x, d$g, p.adjust.method = "nope"), "should be one of") +}) diff --git a/tests/testthat/test-panel.R b/tests/testthat/test-panel.R new file mode 100644 index 0000000..563a9ae --- /dev/null +++ b/tests/testthat/test-panel.R @@ -0,0 +1,35 @@ +# The smoke tests below muffle only that specific warning so that any +# other warning or error is still reported. +ignore_graphical_warnings <- function(expr) { + withCallingHandlers( + expr, + warning = function(w) { + if (grepl("does not name a graphical parameter", conditionMessage(w), fixed = TRUE)) { + invokeRestart("muffleWarning") + } + } + ) +} + +test_that("panel.hist and panel.r2 draw a pairs() plot", { + withr::local_pdf(NULL) + expect_no_error(ignore_graphical_warnings( + pairs( + ~ Ozone + Temp + Wind + Solar.R, + data = airquality, + diag.panel = panel.hist, + upper.panel = panel.r2 + ) + )) +}) + +test_that("panel.hist and panel.r2 accept their optional arguments", { + withr::local_pdf(NULL) + x <- c(1, 3, 2, 5, 4, 6, 8, 7, 9, NA) + y <- c(2, 1, 4, 3, 6, 5, 8, 7, 10, 9) + + plot.new() + expect_no_error(ignore_graphical_warnings(panel.hist(x, col.bar = "red", col = "blue"))) + plot.new() + expect_no_error(ignore_graphical_warnings(panel.r2(x, y, digits = 4, cex.cor = 2))) +}) diff --git a/tests/testthat/test-plr.R b/tests/testthat/test-plr.R new file mode 100644 index 0000000..a909a3b --- /dev/null +++ b/tests/testthat/test-plr.R @@ -0,0 +1,42 @@ +test_that("mfastLmCpp matches marginal simple regressions fitted with lm", { + withr::local_seed(1) + y <- rnorm(10) + x <- matrix(rnorm(30), ncol = 3) + + res <- mfastLmCpp(y, x) + expect_s3_class(res, "data.frame") + expect_named(res, c("coefficients", "stderr", "tstat")) + + expected <- t(sapply(1:3, function(j) coef(summary(lm(y ~ x[, j])))[2, 1:3])) + expect_equal(unname(as.matrix(res)), unname(expected)) +}) + +test_that("mfastLmCpp without intercept matches regressions through the origin", { + withr::local_seed(1) + y <- rnorm(10) + x <- matrix(rnorm(30), ncol = 3) + + res <- mfastLmCpp(y, x, addintercept = FALSE) + expected <- t(sapply(1:3, function(j) coef(summary(lm(y ~ x[, j] - 1)))[1, 1:3])) + expect_equal(unname(as.matrix(res)), unname(expected)) +}) + +test_that("plr on a vector outcome equals mfastLmCpp", { + withr::local_seed(42) + y <- rnorm(50) + x <- matrix(rnorm(150), ncol = 3) + + expect_equal(plr(y, x), mfastLmCpp(y = y, x = x)) + expect_equal(plr(y, x, addintercept = FALSE), mfastLmCpp(y = y, x = x, addintercept = FALSE)) +}) + +test_that("plr on a matrix outcome applies plr to each column", { + withr::local_seed(42) + y <- matrix(rnorm(200), ncol = 4) + x <- matrix(rnorm(150), ncol = 3) + + res <- plr(y, x) + expect_type(res, "list") + expect_length(res, 4) + for (k in 1:4) expect_equal(res[[k]], plr(y[, k], x)) +}) diff --git a/tests/testthat/test-power.binom.test.R b/tests/testthat/test-power.binom.test.R new file mode 100644 index 0000000..f78c7f9 --- /dev/null +++ b/tests/testthat/test-power.binom.test.R @@ -0,0 +1,54 @@ +test_that("power_binom_test two-sided power matches the binom.test rejection region", { + expect_equal(power_binom_test(n = 50, p0 = 0.3, pa = 0.5)$power, binom_test_power(50, 0.3, 0.5)) + expect_equal(power_binom_test(n = 40, p0 = 0.3, pa = 0.1)$power, binom_test_power(40, 0.3, 0.1)) + expect_equal(power_binom_test(n = 20, p0 = 0.5, pa = 0.75)$power, binom_test_power(20, 0.5, 0.75)) +}) + +test_that("power_binom_test one-sided power matches exact binomial tail probabilities", { + # greater: reject when X > qbinom(0.95, n, p0) + expect_equal( + power_binom_test(n = 50, p0 = 0.25, pa = 0.45, alternative = "greater")$power, + pbinom(qbinom(0.95, 50, 0.25), 50, 0.45, lower.tail = FALSE) + ) + # less: reject when X < qbinom(0.05, n, p0) + expect_equal( + power_binom_test(n = 50, p0 = 0.25, pa = 0.10, alternative = "less")$power, + pbinom(qbinom(0.05, 50, 0.25) - 1, 50, 0.10) + ) +}) + +test_that("power_binom_test is vectorised over n", { + expect_equal( + power_binom_test(n = c(40, 50), p0 = 0.3, pa = 0.5)$power, + c(binom_test_power(40, 0.3, 0.5), binom_test_power(50, 0.3, 0.5)) + ) +}) + +test_that("power_binom_test solves for n giving at least the requested power", { + # Exact binomial power is not monotone in n, so only check that the + # returned n achieves the requested power. + res <- power_binom_test(p0 = 0.3, pa = 0.5, power = 0.8) + expect_s3_class(res, "power.htest") + expect_gte(power_binom_test(n = ceiling(res$n), p0 = 0.3, pa = 0.5)$power, 0.8) +}) + +test_that("power_binom_test solves for pa (documented example)", { + res <- power_binom_test(n = 50, p0 = 0.25, power = 0.90, alternative = "less") + expect_equal(res$pa, 0.0954, tolerance = 1e-3) + expect_equal( + power_binom_test(n = 50, p0 = 0.25, pa = res$pa, alternative = "less")$power, + 0.90, + tolerance = 1e-4 + ) +}) + +test_that("power_binom_test validates its arguments", { + expect_error(power_binom_test(n = 50, p0 = 0.5, pa = 0.75, power = 0.9), "exactly one of") + expect_error(power_binom_test(n = 50, p0 = 0.5, pa = 0.75, sig.level = 2), "sig.level") + expect_error(power_binom_test(n = 50, p0 = 0.5, power = 0.9), "symmetry") + expect_error(power_binom_test(n = 50, pa = 0.75, power = 0.9), "symmetry") + expect_error( + power_binom_test(n = 50, p0 = 0.5, pa = 0.75, power = 0.9, sig.level = NULL), + "symmetry" + ) +}) diff --git a/tests/testthat/test-power.mcnemar.test.R b/tests/testthat/test-power.mcnemar.test.R new file mode 100755 index 0000000..5259107 --- /dev/null +++ b/tests/testthat/test-power.mcnemar.test.R @@ -0,0 +1,53 @@ +test_that("Produces validated results", { + expect_equal(round(power_mcnemar_test(paid=0.05, psi=45/5, power=.8)$n), 22.0) + expect_equal(round(power_mcnemar_test(paid=0.05, psi=45/5, power=.8, alternative="one.sided")$n), 17.0) + expect_equal(round(power_mcnemar_test(144, paid=0.25, psi=45/25, method="exact", alternative="one.sided", sig.level=0.025)$power, 2), 0.80) +}) + +test_that("power_mcnemar_test normal approximation matches the closed-form formula", { + # Connor (1987): power = pnorm((sqrt(n paid) (psi - 1) - z sqrt(psi + 1)) / + # sqrt(psi + 1 - paid (psi - 1)^2)) + n <- 60 + paid <- 0.1 + psi <- 2 + expected <- pnorm((sqrt(n * paid) * (psi - 1) - qnorm(0.975) * sqrt(psi + 1)) / + sqrt(psi + 1 - paid * (psi - 1)^2)) + + res <- power_mcnemar_test(n = n, paid = paid, psi = psi) + expect_equal(res$power, expected) + expect_equal(res$power, 0.28941991, tolerance = 1e-7) + expect_identical(res$method, "McNemar paired comparison of proportions approximate power calculation") + expect_identical(res$note, "n is number of pairs") +}) + +test_that("power_mcnemar_test cond.exact equals binomial power for the expected discordant count", { + # Number of discordant pairs: ceiling(n * paid * (1 + psi)) = 18; + # under H1 the split is binomial with p = 1 / (1 + psi) + bc <- 18 + expected <- pbinom(qbinom(0.025, bc, 0.5) - 1, bc, 1 / 3) + + pbinom(qbinom(0.975, bc, 0.5), bc, 1 / 3, lower.tail = FALSE) + + res <- power_mcnemar_test(n = 60, paid = 0.1, psi = 2, method = "cond.exact") + expect_equal(res$power, expected) + expect_match(res$method, "exact conditional") +}) + +test_that("power_mcnemar_test solves for paid, psi and sig.level", { + expected <- power_mcnemar_test(n = 60, paid = 0.1, psi = 2) + power <- expected$power + + expect_equal(power_mcnemar_test(n = 60, psi = 2, power = power)$paid, expected$paid, tolerance = 1e-4) + expect_equal(power_mcnemar_test(n = 60, paid = 0.1, power = power)$psi, expected$psi, tolerance = 1e-4) + expect_equal( + power_mcnemar_test(n = 60, paid = 0.1, psi = 2, power = power, sig.level = NULL)$sig.level, + expected$sig.level, + tolerance = 1e-4 + ) +}) + +test_that("power_mcnemar_test validates its arguments", { + expect_error(power_mcnemar_test(n = 60, paid = .1, psi = 2, power = .8), "exactly one of") + expect_error(power_mcnemar_test(n = 60, paid = .6, psi = 2), "paid is the smallest discordant probability") + expect_error(power_mcnemar_test(n = 60, paid = .1, psi = 0.5), "psi must be 1 or greater") + expect_error(power_mcnemar_test(n = 60, paid = .4, psi = 3), "psi cannot be so big") +}) diff --git a/tests/testthat/test-power.prop.test.R b/tests/testthat/test-power.prop.test.R new file mode 100644 index 0000000..bf60de9 --- /dev/null +++ b/tests/testthat/test-power.prop.test.R @@ -0,0 +1,47 @@ +test_that("power_prop_test with ratio = 1 matches stats::power.prop.test(strict = TRUE)", { + expect_equal( + power_prop_test(n = 50, p1 = 0.5, p2 = 0.7)$power, + power.prop.test(n = 50, p1 = 0.5, p2 = 0.7, strict = TRUE)$power + ) +}) + +test_that("power_prop_test sample size with ratio = 1 matches stats::power.prop.test", { + res <- power_prop_test(p1 = 0.5, p2 = 0.7, power = 0.8) + expect_equal(res$n, power.prop.test(p1 = 0.5, p2 = 0.7, power = 0.8)$n, tolerance = 1e-6) + expect_identical(res$note, "n is number in *each* group") + expect_identical(res$method, "Two-sample comparison of proportions power calculation") +}) + +test_that("power_prop_test sample size for unequal groups (documented example)", { + res <- power_prop_test(p1 = 0.65, p2 = 0.85, power = 0.8, ratio = 2) + + # Closed form: (z_{1-a/2} sqrt(pbar qbar (1 + r)) + z_{power} sqrt(r p1 q1 + p2 q2))^2 / (r d^2) + pbar <- (0.65 + 2 * 0.85) / 3 + n1 <- (qnorm(0.975) * sqrt(pbar * (1 - pbar) * 3) + + qnorm(0.8) * sqrt(2 * 0.65 * 0.35 + 0.85 * 0.15))^2 / (2 * 0.2^2) + + expect_equal(res$n, c(n1, 2 * n1)) + expect_equal(res$n, c(52.06539, 104.13078), tolerance = 1e-6) + expect_identical(res$note, "n is vector of number in each group") + expect_match(res$method, "unequal sample sizes") +}) + +test_that("power_prop_test solves for p1, p2 and ratio consistently", { + n <- power.prop.test(p1 = 0.5, p2 = 0.7, power = 0.8)$n + expect_equal(power_prop_test(n = n, p1 = 0.5, power = 0.8)$p2, 0.7, tolerance = 1e-4) + expect_equal(power_prop_test(n = n, p2 = 0.7, power = 0.8)$p1, 0.5, tolerance = 1e-4) + + res <- power_prop_test(n = 50, p1 = 0.5, p2 = 0.7, power = 0.8, ratio = NULL) + ratio <- res$n[2] / res$n[1] + expect_equal(res$n[1], 50) + expect_equal(power_prop_test(n = 50, p1 = 0.5, p2 = 0.7, ratio = ratio)$power, 0.8, tolerance = 1e-4) +}) + +test_that("power_prop_test validates its arguments", { + expect_error(power_prop_test(n = 50, p1 = 0.5, p2 = 0.7, power = 0.8), "exactly one of") + expect_error(power_prop_test(n = 50, p1 = 0.5, p2 = 0.7, sig.level = 2), "sig.level") + expect_error( + power_prop_test(n = 50, p1 = 0.5, p2 = 0.7, ratio = -1), + "ratio between group sizes must be positive" + ) +}) diff --git a/tests/testthat/test-power.t.test.R b/tests/testthat/test-power.t.test.R new file mode 100644 index 0000000..9c15d8c --- /dev/null +++ b/tests/testthat/test-power.t.test.R @@ -0,0 +1,108 @@ +# With equal group sizes and sd's, power_t_test() must agree with +# stats::power.t.test(strict = TRUE), which serves as the reference. + +test_that("power for equal groups matches stats::power.t.test", { + res <- power_t_test(n = 20, delta = 1, sd = 1) + ref <- stats::power.t.test(n = 20, delta = 1, sd = 1, strict = TRUE) + + expect_s3_class(res, "power.htest") + expect_equal(res$power, ref$power) + expect_equal(res$method, "Two-sample t test power calculation") + expect_equal(res$note, "n is number in *each* group") +}) + +test_that("sample size for equal groups matches stats::power.t.test", { + res <- power_t_test(delta = 1, sd = 1, power = 0.8) + ref <- stats::power.t.test(delta = 1, sd = 1, power = 0.8, strict = TRUE) + expect_equal(res$n, ref$n, tolerance = 1e-6) +}) + +test_that("one-sample, paired and one-sided variants match stats::power.t.test", { + expect_equal( + power_t_test(n = 20, delta = 1, type = "one.sample")$power, + stats::power.t.test(n = 20, delta = 1, type = "one.sample", strict = TRUE)$power + ) + paired <- power_t_test(n = 20, delta = 1, type = "paired", alternative = "one.sided") + expect_equal( + paired$power, + stats::power.t.test(n = 20, delta = 1, type = "paired", alternative = "one.sided")$power + ) + expect_match(paired$note, "*pairs*", fixed = TRUE) +}) + +test_that("strict = FALSE matches the non-strict stats::power.t.test", { + expect_equal( + power_t_test(n = 20, delta = 1, strict = FALSE)$power, + stats::power.t.test(n = 20, delta = 1)$power + ) + # Under H0 the non-strict power is half the significance level + expect_equal(power_t_test(n = 20, delta = 0, strict = FALSE)$power, 0.025) + expect_equal(power_t_test(n = 20, delta = 0, strict = TRUE)$power, 0.05) +}) + +test_that("unequal group sizes use the documented power formula", { + # classical df = n1 + n2 - 2 = 28; ncp = sqrt(n / (1 + 1/ratio)) * delta / sd + res <- power_t_test(n = 10, delta = 1, ratio = 2, df.method = "classical") + nu <- 28 + ncp <- sqrt(10 / 1.5) + q <- qt(0.975, nu) + expected <- pt(q, nu, ncp, lower.tail = FALSE) + pt(-q, nu, ncp) + + expect_equal(res$power, expected) + expect_equal(res$n, c(10, 20)) + expect_equal(res$method, "Two-sample t test power calculation with unequal sample sizes") +}) + +test_that("documented examples give the published sample sizes", { + expect_equal( + power_t_test(delta = 300, sd = 450, power = 0.8, ratio = 4)$n, + c(23.37341, 93.49363), + tolerance = 1e-6 + ) + res <- power_t_test(delta = 300, sd = 450, power = 0.8, sd.ratio = 2) + expect_equal(res$n, c(89.61929, 89.61929), tolerance = 1e-6) + expect_equal(res$sd, c(450, 900)) + expect_equal(res$method, "Two-sample t test power calculation with unequal variances") +}) + +test_that("each NULL parameter is solved so that the target power is reached", { + target <- 0.8 + + delta <- power_t_test(n = 20, sd = 1, power = target)$delta + expect_equal(power_t_test(n = 20, delta = delta, sd = 1)$power, target, tolerance = 1e-4) + + sd <- power_t_test(n = 20, delta = 1, sd = NULL, power = target)$sd + expect_equal(power_t_test(n = 20, delta = 1, sd = sd)$power, target, tolerance = 1e-4) + + alpha <- power_t_test(n = 20, delta = 1, sig.level = NULL, power = target)$sig.level + # uniroot's default tolerance on the sig.level scale is ~1e-4 + expect_equal(power_t_test(n = 20, delta = 1, sig.level = alpha)$power, target, tolerance = 1e-3) + + res <- power_t_test(n = 15, delta = 1, power = target, ratio = NULL) + expect_equal(res$n[1], 15) + ratio <- res$n[2] / 15 + expect_gt(ratio, 1) + expect_equal(power_t_test(n = 15, delta = 1, ratio = ratio)$power, target, tolerance = 1e-4) + + res <- power_t_test(n = 20, delta = 1, power = target, sd.ratio = NULL) + expect_equal(res$sd[1], 1) + expect_equal(power_t_test(n = 20, delta = 1, sd.ratio = res$sd[2])$power, target, tolerance = 1e-4) +}) + +test_that("a negative delta is treated as its absolute value in the two-sided case", { + expect_equal(power_t_test(n = 20, delta = -1)$delta, 1) + expect_equal(power_t_test(n = 20, delta = -1)$power, power_t_test(n = 20, delta = 1)$power) +}) + +test_that("invalid argument combinations raise informative errors", { + expect_error( + power_t_test(n = 20, delta = 1, power = 0.8), + "exactly one of n, delta, sd, power, sig.level, ratio and sd.ratio must be NULL" + ) + expect_error( + power_t_test(n = 20, delta = 1, power = 0.8, type = "paired"), + "exactly one of n, delta, sd, power, and sig.level must be NULL" + ) + expect_error(power_t_test(n = 20, delta = 1, ratio = 0.5), "cannot be less than 1") + expect_error(power_t_test(n = 20, delta = 1, sd.ratio = -1), "must be positive") +}) diff --git a/tests/testthat/test-prepost.R b/tests/testthat/test-prepost.R new file mode 100644 index 0000000..b9e3e2b --- /dev/null +++ b/tests/testthat/test-prepost.R @@ -0,0 +1,63 @@ +# Example data from the documentation (Altman) +expo <- c(rep(1, 9), rep(0, 7)) +bp1w <- c(137, 120, 141, 137, 140, 144, 134, 123, 142, 139, 134, 136, 151, 147, 137, 149) +bp_base <- c(147, 129, 158, 164, 134, 155, 151, 141, 153, 133, 129, 152, 161, 154, 141, 156) + +test_that("documented example returns the expected htest", { + res <- prepost.test(bp_base, bp1w, expo) + + expect_s3_class(res, "htest") + expect_named(res, c("statistic", "se", "p.value", "conf.int", "estimate", "method")) + expect_equal(unname(res$estimate), -7.176388055, tolerance = 1e-8) + expect_equal(res$se, 2.522606035, tolerance = 1e-8) + expect_equal(unname(res$statistic), -2.844831082, tolerance = 1e-8) + expect_equal(unname(res$p.value), 0.004443498039, tolerance = 1e-8) + expect_equal(as.vector(res$conf.int), c(-12.120605032, -2.232171079), tolerance = 1e-8) +}) + +test_that("without missing data the estimate is the mean difference of arm-wise predictions", { + # With every post value observed the augmentation terms vanish and the + # estimator reduces to mean(ehat1 - ehat0), where ehatk are predictions + # from a regression of post on baseline within arm k. + newdata <- data.frame(bp_base = bp_base) + ehat1 <- predict(lm(bp1w ~ bp_base, subset = expo == 1), newdata) + ehat0 <- predict(lm(bp1w ~ bp_base, subset = expo == 0), newdata) + + res <- prepost.test(bp_base, bp1w, expo) + expect_equal(unname(res$estimate), mean(ehat1 - ehat0)) +}) + +test_that("statistic, p-value and confidence interval are internally consistent", { + res <- prepost.test(bp_base, bp1w, expo, conf.level = 0.9) + + expect_equal(unname(res$statistic), unname(res$estimate) / res$se) + expect_equal(unname(res$p.value), 2 * pnorm(-abs(unname(res$statistic)))) + expect_equal( + as.vector(res$conf.int), + unname(res$estimate) + c(-1, 1) * qnorm(0.95) * res$se + ) + expect_equal(attr(res$conf.int, "conf.level"), 0.9) +}) + +test_that("a fixed delta is used instead of the observed treated proportion", { + res <- prepost.test(bp_base, bp1w, expo, delta = 0.5) + expect_equal(unname(res$estimate), -7.176388055, tolerance = 1e-8) + expect_equal(res$se, 2.64499988, tolerance = 1e-8) + + # delta equal to the observed proportion reproduces the default + expect_equal(prepost.test(bp_base, bp1w, expo, delta = 9 / 16), prepost.test(bp_base, bp1w, expo)) +}) + +test_that("a logical treatment vector gives the same result as 0/1", { + expect_equal(prepost.test(bp_base, bp1w, expo == 1), prepost.test(bp_base, bp1w, expo)) +}) + +test_that("invalid inputs raise informative errors", { + expect_error( + prepost.test(bp_base, bp1w, c(rep(1, 6), rep(2, 5), rep(3, 5))), + "exactly two treatments" + ) + expect_error(prepost.test(bp_base, bp1w, ifelse(expo == 1, "T", "C")), "treatment must be numeric") + expect_error(prepost.test(bp_base, bp1w, factor(expo)), "treatment must be numeric") + expect_error(prepost.test(bp_base, bp1w, expo, conf.level = 2), "'conf.level' must be a single number") +}) diff --git a/tests/testthat/test-qic.R b/tests/testthat/test-qic.R new file mode 100644 index 0000000..0d8f40f --- /dev/null +++ b/tests/testthat/test-qic.R @@ -0,0 +1,86 @@ +# MESS::QIC() is checked against geepack::QIC(), which implements the same +# criterion. Always call MESS::QIC explicitly because geepack exports a QIC() +# generic too. +# +# Models are fitted with `data = ::` so the stored call can be +# re-evaluated by QIC's internal refit from any environment (see B09 for the +# case where the data lives in a local variable). + +qic_names <- c("QIC", "QICu", "Quasi Lik", "CIC", "params", "QICC") + +test_that("QIC for a binomial geeglm matches geepack::QIC", { + fit <- geepack::geeglm(resp ~ age + smoke, id = id, data = geepack::ohio, + family = binomial, corstr = "exchangeable") + res <- MESS::QIC(fit) + + expect_named(res, qic_names) + expect_equal(res, geepack::QIC(fit)) + expect_equal(unname(res["params"]), 3) + expect_equal(unname(res["QIC"]), 1829.482937, tolerance = 1e-8) +}) + +test_that("QIC for gaussian, poisson and Gamma geeglm fits matches geepack::QIC", { + gaussian_fit <- geepack::geeglm(Weight ~ Time, id = Pig, data = geepack::dietox, + family = gaussian, corstr = "ar1") + expect_equal(MESS::QIC(gaussian_fit), geepack::QIC(gaussian_fit)) + + poisson_fit <- geepack::geeglm(y ~ trt + lbase, id = subject, data = MASS::epil, + family = poisson, corstr = "exchangeable") + expect_equal(MESS::QIC(poisson_fit), geepack::QIC(poisson_fit)) + + gamma_fit <- geepack::geeglm(Weight ~ Time, id = Pig, data = geepack::dietox, + family = Gamma, corstr = "ar1") + expect_equal(MESS::QIC(gamma_fit), geepack::QIC(gamma_fit)) +}) + +test_that("several models passed through ... give one row per model", { + fit1 <- geepack::geeglm(resp ~ age + smoke, id = id, data = geepack::ohio, + family = binomial, corstr = "exchangeable") + fit2 <- geepack::geeglm(resp ~ age, id = id, data = geepack::ohio, + family = binomial, corstr = "exchangeable") + + res <- MESS::QIC(fit1, model2 = fit2) + + expect_equal(dim(res), c(2, 6)) + expect_equal(colnames(res), qic_names) + expect_equal(rownames(res), c("fit1", "fit2")) + expect_equal(res[1, ], geepack::QIC(fit1)) + expect_equal(res[2, ], geepack::QIC(fit2)) +}) + +test_that("comparing models fitted to different numbers of observations warns", { + fit1 <- geepack::geeglm(resp ~ age, id = id, data = geepack::ohio, family = binomial) + fit2 <- geepack::geeglm(resp ~ age, id = id, data = geepack::ohio[geepack::ohio$smoke == 1, ], + family = binomial) + expect_warning( + MESS::QIC(fit1, model2 = fit2), + "models are not all fitted to the same number of observations" + ) +}) + +test_that("QIC for a geekin fit equals QIC for the equivalent exchangeable geeglm", { + # geekin() evaluates geeglm() in the caller's frame, so geepack must be attached (B35) + withr::local_package("geepack") + pig <- geepack::dietox$Pig[1:120] + # A block-diagonal matrix of ones per cluster is equivalent to an + # exchangeable working correlation + block <- outer(pig, pig, "==") * 1 + + kin_fit <- geekin(Weight ~ Time, id = geepack::dietox$Pig[1:120], + data = geepack::dietox[1:120, ], varlist = list(block)) + exch_fit <- geepack::geeglm(Weight ~ Time, id = Pig, data = geepack::dietox[1:120, ], + corstr = "exchangeable") + + expect_equal(MESS::QIC(kin_fit), geepack::QIC(exch_fit), tolerance = 1e-6) +}) + +test_that("an unsupported family raises an error", { + fit <- geepack::geeglm(Weight ~ Time, id = Pig, data = geepack::dietox) + fit$family$family <- "unsupported" + expect_error(MESS::QIC(fit), "distribution not recognized") +}) + +test_that("non-geeglm objects are rejected", { + expect_error(MESS::QIC(structure(list(), class = "geekin")), "QIC requires a geekin object") + expect_error(MESS::QIC(lm(dist ~ speed, data = cars)), class = "error") +}) diff --git a/tests/testthat/test-residualplot.R b/tests/testthat/test-residualplot.R new file mode 100644 index 0000000..931786a --- /dev/null +++ b/tests/testthat/test-residualplot.R @@ -0,0 +1,71 @@ +# Small residual data set with one point outside +/- 1.96 (x = 4) +res_x <- 1:10 +res_y <- c(0.1, -0.2, 0.3, 2.5, -0.1, 0.2, -0.3, 0.1, 0, -0.2) + +geom_classes <- function(p) { + unname(vapply(p$layers, function(l) class(l$geom)[1], character(1))) +} + +## Base-graphics residualplot() -------------------------------------------- + +test_that("residualplot draws for numeric vectors, lm and glm fits and returns invisible NULL", { + withr::local_pdf(NULL) + + expect_invisible(res <- residualplot(res_x, res_y)) + expect_null(res) + expect_null(residualplot(res_x, res_y, candy = FALSE)) + expect_null(residualplot(res_x, res_y, col.alpha = 0, ylim = c(-5, 5))) + # three or fewer unique x values: no smoothing spline is added + expect_null(residualplot(rep(1:3, 4), rep(c(-1, 0, 1), 4))) + + expect_null(residualplot(lm(Volume ~ Girth + Height, data = trees))) + expect_null(residualplot(glm(am ~ hp, data = mtcars, family = binomial))) +}) + +test_that("residualplot requires y for the default method", { + expect_error(residualplot(1:5), "y must be specified") +}) + +## ggplot2 residual_plot() -------------------------------------------------- + +test_that("residual_plot with candy = FALSE only draws the points", { + p <- residual_plot(res_x, res_y, candy = FALSE) + expect_s3_class(p, "ggplot") + expect_equal(geom_classes(p), "GeomPoint") +}) + +test_that("residual_plot with candy adds spline, ribbon and outlier layers", { + p <- residual_plot(res_x, res_y) + expect_equal(geom_classes(p), c("GeomPoint", "GeomLine", "GeomRibbon", "GeomPoint", "GeomPoint")) + + # Without points outside +/- 1.96 the outlier layer is omitted + p_no_outlier <- residual_plot(res_x, c(0.1, -0.2, 0.3, 0.5, -0.1, 0.2, -0.3, 0.1, 0, -0.2)) + expect_equal(geom_classes(p_no_outlier), c("GeomPoint", "GeomLine", "GeomRibbon", "GeomPoint")) +}) + +test_that("residual_plot ribbon is +/- 1.96 local SD within the bandwidth window", { + p <- residual_plot(res_x, res_y) + ribbon <- ggplot2::layer_data(p, 3) + + # window = 0.3 * (10 - 1) / 2 = 1.35, so at x = 1 the window holds x = 1, 2 + expect_equal(ribbon$ymax[1], 1.96 * sd(res_y[1:2])) + # at x = 5 the window holds x = 4, 5, 6 + expect_equal(ribbon$ymax[5], 1.96 * sd(res_y[4:6])) + expect_equal(ribbon$ymin, -ribbon$ymax) +}) + +test_that("residual_plot uses studentized/standardized residuals for lm and glm fits", { + lm_fit <- lm(Volume ~ Girth + Height, data = trees) + p_lm <- residual_plot(lm_fit, candy = FALSE) + expect_equal(p_lm$data$x, unname(predict(lm_fit))) + expect_equal(p_lm$data$y, unname(rstudent(lm_fit))) + + glm_fit <- glm(am ~ hp, data = mtcars, family = binomial) + p_glm <- residual_plot(glm_fit, candy = FALSE) + expect_equal(p_glm$data$x, unname(predict(glm_fit, type = "link"))) + expect_equal(p_glm$data$y, unname(rstandard(glm_fit))) +}) + +test_that("residual_plot requires y for the default method", { + expect_error(residual_plot(1:5), "y must be specified") +}) diff --git a/tests/testthat/test-rmvtnorm.pedigree.R b/tests/testthat/test-rmvtnorm.pedigree.R new file mode 100644 index 0000000..e81782c --- /dev/null +++ b/tests/testthat/test-rmvtnorm.pedigree.R @@ -0,0 +1,71 @@ +# Nuclear family: parents 1 and 2 with three sons; 3 and 4 are MZ twins. +make_twin_pedigree <- function() { + kinship2::pedigree( + id = 1:5, + dadid = c(NA, NA, 1, 1, 1), + momid = c(NA, NA, 2, 2, 2), + sex = c("male", "female", "male", "male", "male"), + relation = data.frame(id1 = 3, id2 = 4, code = 1) + ) +} + +# Additive relationship matrix (2 x kinship) of the twin pedigree, by hand: +# parent-child and full sibs 1/2, MZ twins 1, unrelated parents 0. +twin_relationship <- matrix(c( + 1.0, 0.0, 0.5, 0.5, 0.5, + 0.0, 1.0, 0.5, 0.5, 0.5, + 0.5, 0.5, 1.0, 1.0, 0.5, + 0.5, 0.5, 1.0, 1.0, 0.5, + 0.5, 0.5, 0.5, 0.5, 1.0 +), nrow = 5, byrow = TRUE) + +test_that("the twin pedigree has the expected relationship matrix", { + expect_equal(unname(2 * kinship2::kinship(make_twin_pedigree())), twin_relationship) +}) + +test_that("rmvtnorm.pedigree draws from N(0, (1-h2-c2) I + h2 A + c2 J)", { + ped <- make_twin_pedigree() + h2 <- 0.3 + c2 <- 0.2 + sigma <- (1 - h2 - c2) * diag(5) + h2 * twin_relationship + c2 + + withr::local_seed(123) + res <- rmvtnorm.pedigree(4, ped, h2 = h2, c2 = c2) + withr::local_seed(123) + expected <- t(mvtnorm::rmvnorm(4, mean = rep(0, 5), sigma = sigma)) + + expect_equal(dim(res), c(5, 4)) + expect_equal(unname(res), unname(expected)) +}) + +test_that("rmvtnorm.pedigree with no genetic or shared effects gives independent normals", { + withr::local_seed(1) + res <- rmvtnorm.pedigree(3, make_twin_pedigree()) + withr::local_seed(1) + expect_equal(res, t(mvtnorm::rmvnorm(3, mean = rep(0, 5), sigma = diag(5)))) +}) + +test_that("rmvt.pedigree draws from a multivariate t with the same scale matrix", { + ped <- make_twin_pedigree() + h2 <- 0.3 + c2 <- 0.2 + sigma <- (1 - h2 - c2) * diag(5) + h2 * twin_relationship + c2 + + withr::local_seed(99) + res <- rmvt.pedigree(4, ped, h2 = h2, c2 = c2, df = 4) + withr::local_seed(99) + expected <- t(mvtnorm::rmvt(4, sigma = sigma, df = 4)) + + expect_equal(dim(res), c(5, 4)) + expect_equal(unname(res), unname(expected)) +}) + +test_that("both simulators validate their inputs", { + ped <- make_twin_pedigree() + for (sim in list(rmvtnorm.pedigree, rmvt.pedigree)) { + expect_error(sim(2, ped, h2 = 0.6, c2 = 0.5), "input parameters wrong") + expect_error(sim(2, ped, h2 = -0.1), "input parameters wrong") + expect_error(sim(2, ped, d2 = 0.1), "cannot handle d2") + expect_error(sim(2, list(id = 1:5)), "requires a single pedigree as input") + } +}) diff --git a/tests/testthat/test-rnormperfect.R b/tests/testthat/test-rnormperfect.R new file mode 100644 index 0000000..7fff49c --- /dev/null +++ b/tests/testthat/test-rnormperfect.R @@ -0,0 +1,17 @@ +test_that("values are the normal quantiles at i / (n + 1)", { + expect_equal(rnorm_perfect(4), qnorm((1:4) / 5)) + expect_equal(rnorm_perfect(5, sd = 2), 2 * qnorm((1:5) / 6)) + # middle value of an odd-length sample is exactly the mean + expect_equal(rnorm_perfect(5)[3], 0) +}) + +test_that("a vector n uses its length, like rnorm()", { + expect_equal(rnorm_perfect(c(10, 20, 30)), rnorm_perfect(3)) +}) + +test_that("invalid arguments raise errors", { + expect_error(rnorm_perfect("a"), "is.numeric\\(n\\) is not TRUE") + expect_error(rnorm_perfect(0), "n > 0 is not TRUE") + expect_error(rnorm_perfect(5, mean = c(0, 1)), "length\\(mean\\) == 1 is not TRUE") + expect_error(rnorm_perfect(5, sd = c(1, 2)), "length\\(sd\\) == 1 is not TRUE") +}) diff --git a/tests/testthat/test-rootonorm.R b/tests/testthat/test-rootonorm.R new file mode 100644 index 0000000..85c6420 --- /dev/null +++ b/tests/testthat/test-rootonorm.R @@ -0,0 +1,29 @@ +# Fixed data with known bin counts: (0,1] -> 1, (1,2] -> 2, (2,3] -> 3 +root_x <- c(1, 2, 2, 3, 3, 3) + +test_that("rootonorm invisibly returns the histogram counts", { + withr::local_pdf(NULL) + + expect_invisible(res <- rootonorm(root_x, breaks = 0:3)) + expect_equal(res, c(1, 2, 3)) +}) + +test_that("rootonorm counts match hist() for the default breaks", { + withr::local_pdf(NULL) + withr::local_seed(1) + x <- rnorm(200) + expect_equal(rootonorm(x), hist(x, plot = FALSE)$counts) +}) + +test_that("all plot types, scales and reference distributions can be drawn", { + withr::local_pdf(NULL) + + expect_equal(rootonorm(root_x, breaks = 0:3, type = "deviation"), c(1, 2, 3)) + expect_equal(rootonorm(root_x, breaks = 0:3, scale = "raw"), c(1, 2, 3)) + expect_equal(rootonorm(root_x, breaks = 0:3, mu = 1, s = 2, zeroline = FALSE, ylim = c(-1, 3)), c(1, 2, 3)) +}) + +test_that("invalid inputs raise informative errors", { + expect_error(rootonorm("a"), "'x' must be numeric") + expect_error(rootonorm(root_x, breaks = c(0, 1, 3)), "breaks must be equally spaced") +}) diff --git a/tests/testthat/test-round_percent.R b/tests/testthat/test-round_percent.R new file mode 100644 index 0000000..a26db33 --- /dev/null +++ b/tests/testthat/test-round_percent.R @@ -0,0 +1,25 @@ +test_that("documented example gives the expected rounded percentages", { + f <- c(1, 2, 1, 3, 2, 1, 2, 3, 1) + # exact percentages are 6.25, 12.5, 18.75; the missing 1 point after + # flooring goes to the largest remainders (ties broken by position) + expect_equal(round_percent(f, ties = "last"), c(6, 12, 6, 19, 13, 6, 13, 19, 6)) +}) + +test_that("random tie-breaking always sums to 100", { + withr::local_seed(1) + res <- round_percent(c(1, 1, 1)) + expect_equal(sort(res), c(33, 33, 34)) + expect_equal(sum(res), 100) +}) + +test_that("decimals sets the precision and the result still sums to 100", { + # 33.333... each: floor gives 33.3 x 3 = 99.9, the last element gets the extra 0.1 + expect_equal(round_percent(c(1, 1, 1), decimals = 1, ties = "last"), c(33.3, 33.3, 33.4)) + expect_equal(round_percent(c(10, 20, 30, 40), decimals = 1), c(10, 20, 30, 40)) +}) + +test_that("invalid inputs raise informative errors", { + expect_error(round_percent(c(-1, 2)), "only works on non-negative vectors") + expect_error(round_percent(c("a", "b")), "only works on numeric vectors") + expect_error(round_percent(c(1, 2), decimals = -1), "non-negative integer") +}) diff --git a/tests/testthat/test-rowmeanscond.R b/tests/testthat/test-rowmeanscond.R new file mode 100644 index 0000000..934156d --- /dev/null +++ b/tests/testthat/test-rowmeanscond.R @@ -0,0 +1,22 @@ +test_that("documented example: row means over the non-missing values", { + expect_equal(conditional_rowMeans(1:5, c(1:4, NA), c(1:3, NA, NA)), c(1, 2, 3, 4, 5)) +}) + +test_that("rows with fewer than minobs observations are NA", { + x <- c(1, NA, 3) + y <- c(3, NA, NA) + z <- c(5, 6, NA) + + # minobs = 1 (default): only the all-missing row is NA + expect_equal(conditional_rowMeans(c(1, NA), c(NA, NA)), c(1, NA)) + expect_equal(conditional_rowMeans(x, y, z), c(3, 6, 3)) + expect_equal(conditional_rowMeans(x, y, z, minobs = 2), c(3, NA, NA)) + expect_equal(conditional_rowMeans(x, y, z, minobs = 3), c(3, NA, NA)) + expect_equal(conditional_rowMeans(1:5, c(1:4, NA), c(1:3, NA, NA), minobs = 2), c(1, 2, 3, 4, NA)) +}) + +test_that("a matrix argument is treated as several columns", { + m <- cbind(c(1, NA), c(3, 4)) + expect_equal(conditional_rowMeans(m), c(2, 4)) + expect_equal(conditional_rowMeans(m, minobs = 2), c(2, NA)) +}) diff --git a/tests/testthat/test-rud.R b/tests/testthat/test-rud.R new file mode 100644 index 0000000..3e7c333 --- /dev/null +++ b/tests/testthat/test-rud.R @@ -0,0 +1,40 @@ +test_that("rud returns n group allocations from the available groups", { + withr::local_seed(1) + res <- rud(10, alpha = c(1, 1, 10), beta = 5) + expect_type(res, "integer") + expect_length(res, 10) + expect_true(all(res %in% 1:3)) +}) + +test_that("allocation follows the urn weights", { + # A group with zero weight is never drawn while beta = 0 keeps it at zero + expect_equal(rud(5, alpha = c(1, 0), beta = 0), rep(1L, 5)) + expect_equal(rud(5, alpha = c(0, 1), beta = 0), rep(2L, 5)) + + # After the forced first draw of group 2, beta is added to the *other* + # group, so the urn becomes c(1e6, 1) and group 1 is (almost surely) next + withr::local_seed(1) + expect_equal(rud(2, alpha = c(0, 1), beta = 1e6), c(2L, 1L)) +}) + +test_that("the same seed gives the same allocation", { + withr::local_seed(42) + first <- rud(20) + withr::local_seed(42) + expect_equal(rud(20), first) +}) + +test_that("data.frame = TRUE returns ids, groups and treatment labels", { + withr::local_seed(4) + res <- rud(6, labels = c("Drug", "Placebo"), data.frame = TRUE, startid = 100) + + expect_s3_class(res, "data.frame") + expect_named(res, c("id", "group", "treatment")) + expect_equal(res$id, 100:105) + expect_equal(res$treatment, c("Drug", "Placebo")[res$group]) +}) + +test_that("invalid inputs raise informative errors", { + expect_error(rud(5, alpha = 1), "length of at least 2") + expect_error(rud(5, alpha = c(1, 1, 1), labels = c("A", "B")), "length of labels must be the same") +}) diff --git a/tests/testthat/test-screener.R b/tests/testthat/test-screener.R new file mode 100644 index 0000000..85896b2 --- /dev/null +++ b/tests/testthat/test-screener.R @@ -0,0 +1,41 @@ +# With x = I and y = (3, 2, 1), |x'y| = (3, 2, 1) and lambdamax = 3. +# The global strong rule discards variable j when |x_j'y| < 2 * lambda - lambdamax. + +test_that("global strong rule returns the indices with |x'y| below the criterion", { + res <- screen_variables(diag(3), c(3, 2, 1), lambda = c(2, 2.5, 3)) + + expect_named(res, c("lambda", "selected", "method")) + expect_equal(res$lambda, c(2, 2.5, 3)) + expect_equal(res$method, "global-strong") + # criteria 1, 2, 3 + expect_equal(res$selected, list(integer(0), 3L, 2:3)) +}) + +test_that("the screening agrees with the rule on random data", { + withr::local_seed(10) + x <- matrix(rnorm(30 * 10), nrow = 30) + y <- rnorm(30, mean = x[, 1]) + score <- abs(drop(crossprod(x, y))) + lambda <- max(score) * c(0.6, 0.9) + + res <- screen_variables(x, y, lambda = lambda) + expect_equal(res$selected, lapply(lambda, function(l) which(score < 2 * l - max(score)))) +}) + +test_that("a table is accepted as x", { + tbl <- as.table(diag(3)) + expect_equal( + screen_variables(tbl, c(3, 2, 1), lambda = c(2.5, 3))$selected, + list(3L, 2:3) + ) +}) + +test_that("invalid inputs raise informative errors", { + x <- diag(3) + y <- c(3, 2, 1) + expect_error(screen_variables(as.data.frame(x), y), "needs matrix or table as input") + expect_error(screen_variables(as.vector(x), y), "needs matrix or table as input") + expect_error(screen_variables(x, y, lambda = 0), "lambda must be positive") + expect_error(screen_variables(x, y, lambda = c(0.1, -1)), "lambda must be positive") + expect_error(screen_variables(x, y, method = "unknown"), "'arg' should be one of") +}) diff --git a/tests/testthat/test-segregate.genes.R b/tests/testthat/test-segregate.genes.R new file mode 100644 index 0000000..1aa4fb2 --- /dev/null +++ b/tests/testthat/test-segregate.genes.R @@ -0,0 +1,69 @@ +test_that("segregate.genes returns one column of genotypes per marker", { + ped <- make_pedigree() + withr::local_seed(42) + res <- segregate.genes(ped, c(0.1, 0.3, 0.5)) + + expect_equal(class(res), c("matrix", "array")) + expect_equal(dim(res), c(14, 3)) + expect_equal(colnames(res), c("gene1", "gene2", "gene3")) + expect_true(all(res %in% 0:2)) +}) + +test_that("allele frequencies 0 and 1 give monomorphic markers", { + ped <- make_pedigree() + res <- segregate.genes(ped, c(0, 1)) + expect_equal(unname(res[, "gene1"]), rep(0, 14)) + expect_equal(unname(res[, "gene2"]), rep(2, 14)) +}) + +test_that("offspring genotypes are Mendelian-consistent with their parents", { + ped <- make_pedigree() + withr::local_seed(1) + res <- segregate.genes(ped, rep(0.5, 50)) + + child <- ped$findex > 0 + dad <- res[ped$findex[child], , drop = FALSE] + mom <- res[ped$mindex[child], , drop = FALSE] + kids <- res[child, , drop = FALSE] + # each parent transmits one allele: always if homozygous for it (2), never if 0 + expect_true(all(kids >= (dad == 2) + (mom == 2))) + expect_true(all(kids <= (dad > 0) + (mom > 0))) +}) + +test_that("MZ twins receive identical genotypes", { + ped <- kinship2::pedigree( + id = 1:5, + dadid = c(NA, NA, 1, 1, 1), + momid = c(NA, NA, 2, 2, 2), + sex = c("male", "female", "male", "male", "male"), + relation = data.frame(id1 = 3, id2 = 4, code = 1) + ) + withr::local_seed(123) + res <- segregate.genes(ped, rep(0.5, 20)) + expect_equal(res[3, ], res[4, ]) +}) + +test_that("a pedigree of founders only returns a data.frame", { + ped <- kinship2::pedigree(id = 1:3, dadid = rep(NA, 3), momid = rep(NA, 3), + sex = c("male", "female", "male")) + res <- segregate.genes(ped, c(0, 1)) + + expect_s3_class(res, "data.frame") + expect_equal(res, data.frame(gene1 = rep(0, 3), gene2 = rep(2, 3))) +}) + +test_that("invalid inputs raise informative errors", { + ped <- make_pedigree() + expect_error(segregate.genes(ped, c(-0.1, 0.5)), "minor allele frequencies must be in the range") + expect_error(segregate.genes(ped, 1.5), "minor allele frequencies must be in the range") + expect_error(segregate.genes(list(id = 1:3), 0.1), "requires a single pedigree as input") + + peds <- kinship2::pedigree( + id = c(1, 2, 3, 11, 12, 13), + dadid = c(NA, NA, 1, NA, NA, 11), + momid = c(NA, NA, 2, NA, NA, 12), + sex = c("male", "female", "male", "male", "female", "male"), + famid = c("A", "A", "A", "B", "B", "B") + ) + expect_error(segregate.genes(peds, 0.1), "requires a single pedigree as input") +}) diff --git a/tests/testthat/test-sinv.R b/tests/testthat/test-sinv.R new file mode 100644 index 0000000..2e2803b --- /dev/null +++ b/tests/testthat/test-sinv.R @@ -0,0 +1,16 @@ +test_that("sinv inverts a symmetric positive-definite matrix", { + m <- matrix(c(1, 0, .5, .5, + 0, 1, .5, .5, + .5, .5, 1, .5, + .5, .5, .5, 1), 4) + expect_equal(sinv(m), solve(m)) + expect_equal(sinv(m) %*% m, diag(4)) +}) + +test_that("sinv of a diagonal matrix inverts the diagonal", { + expect_equal(sinv(diag(c(2, 4, 5))), diag(c(0.5, 0.25, 0.2))) +}) + +test_that("a matrix that is not positive definite raises an error", { + expect_error(sinv(matrix(c(1, 2, 2, 1), 2)), "not positive") +}) diff --git a/tests/testthat/test-usd.R b/tests/testthat/test-usd.R new file mode 100644 index 0000000..317bcde --- /dev/null +++ b/tests/testthat/test-usd.R @@ -0,0 +1,19 @@ +# usd(x) = sd(x) / (1 - 1/(4n) - 7/(32n^2) - 19/(128n^3)) + +test_that("usd applies the small-sample correction to sd", { + n <- 5 + correction <- 1 - 1 / (4 * n) - 7 / (32 * n^2) - 19 / (128 * n^3) + expect_equal(usd(1:5), sd(1:5) / correction) + # documented value + expect_equal(usd(1:5), 1.681951, tolerance = 1e-6) +}) + +test_that("na.rm drops missing values and uses the reduced n", { + expect_equal(usd(c(1:5, NA), na.rm = TRUE), usd(1:5)) + expect_equal(usd(c(1:5, NA)), NA_real_) +}) + +test_that("fewer than two observations give NA", { + expect_equal(usd(1), NA_real_) + expect_equal(usd(numeric(0)), NA_real_) +}) diff --git a/tests/testthat/test-wallyplot.R b/tests/testthat/test-wallyplot.R new file mode 100644 index 0000000..520da80 --- /dev/null +++ b/tests/testthat/test-wallyplot.R @@ -0,0 +1,55 @@ +# All tests use hide = FALSE: with hide = TRUE the plot waits for +# via readline(), and the original data is always drawn in the first panel. + +# Panel function that plots and records the y values it is asked to draw +recording_panel <- function(env) { + force(env) + function(x, y, ...) { + env$calls <- c(env$calls, list(y)) + plot(x, y, ...) + } +} + +test_that("wallyplot draws 9 panels with the original data first and returns invisible NULL", { + withr::local_pdf(NULL) + withr::local_seed(1) + rec <- new.env() + y <- rnorm(20) + + expect_invisible(res <- wallyplot(1:20, y, FUN = recording_panel(rec), hide = FALSE)) + expect_null(res) + expect_length(rec$calls, 9) + expect_equal(rec$calls[[1]], y) +}) + +test_that("a 9-column matrix of y values is plotted as given", { + withr::local_pdf(NULL) + rec <- new.env() + y <- matrix(1:90, ncol = 9) + + wallyplot(1:10, y, FUN = recording_panel(rec), hide = FALSE) + expect_equal(rec$calls, lapply(1:9, function(j) y[, j])) +}) + +test_that("the default residualplot panel function draws without error", { + withr::local_pdf(NULL) + withr::local_seed(2) + expect_null(wallyplot(1:20, rnorm(20), hide = FALSE)) +}) + +test_that("wallyplot for an lm fit shows the standardized residuals first", { + withr::local_pdf(NULL) + withr::local_seed(3) + rec <- new.env() + fit <- lm(Volume ~ Girth + Height, data = trees) + + expect_null(wallyplot(fit, FUN = recording_panel(rec), hide = FALSE)) + expect_length(rec$calls, 9) + expect_equal(rec$calls[[1]], rstandard(fit)) +}) + +test_that("invalid inputs raise informative errors", { + expect_error(wallyplot(1:20, rnorm(15), hide = FALSE), "must be a vector and matrix") + expect_error(wallyplot(1:20, matrix(0, 20, 5), hide = FALSE), "y must be a matrix with 9 columns") + expect_error(wallyplot(1:20, matrix(0, 15, 9), hide = FALSE), "x and y does not conform") +}) diff --git a/tests/testthat/test-writexml.R b/tests/testthat/test-writexml.R new file mode 100644 index 0000000..74defc0 --- /dev/null +++ b/tests/testthat/test-writexml.R @@ -0,0 +1,40 @@ +xml_data <- data.frame(a = 1:2, b = c("x", "y")) + +test_that("write.xml writes one collapsed row element per observation", { + path <- withr::local_tempfile(fileext = ".xml") + + expect_invisible(res <- write.xml(xml_data, file = path)) + expect_equal(res, 0) + expect_equal(readLines(path), c( + '', + "", + " 1x", + " 2y", + "" + )) +}) + +test_that("collapse = FALSE writes each field on its own indented line", { + path <- withr::local_tempfile(fileext = ".xml") + write.xml(xml_data, file = path, collapse = FALSE) + + expect_equal(readLines(path), c( + '', + "", + " ", " 1", " x", " ", + " ", " 2", " y", " ", + "" + )) +}) + +test_that("factor and decimal columns are written as text", { + path <- withr::local_tempfile(fileext = ".xml") + write.xml(data.frame(f = factor("lvl"), n = 1.5), file = path) + expect_equal(readLines(path)[3], " lvl1.5") +}) + +test_that("invalid inputs raise informative errors", { + expect_error(write.xml(xml_data), "filename not specified") + path <- withr::local_tempfile(fileext = ".xml") + expect_error(write.xml(1:5, file = path), "data must be a data frame") +}) diff --git a/tests/testthat/testauc.R b/tests/testthat/testauc.R deleted file mode 100755 index 6db1b02..0000000 --- a/tests/testthat/testauc.R +++ /dev/null @@ -1,17 +0,0 @@ -context("Test auc") - - -## -## All of these checks should provide the correct results -## - -test_that("Produces validated results", { - expect_equal(auc(1:4, c(0, 1, 1, 5)), 4.5) - expect_equal(auc(1:4, -c(0, 1, 1, 5)), -4.5) - expect_equal(auc(1:4, -c(0, 1, 1, 5), absolutearea=TRUE), 4.5) - expect_equal(auc(0:4, c(0, 0, 1, -1, 0)), 0) - expect_equal(auc(0:4, c(0, 0, 1, -1, 0), absolutearea=TRUE), 1.5) - expect_equal(auc(0:4, c(0, 0, 1, -1, 0), absolutearea=TRUE, subdivisions =150), 1.5) - expect_equal(auc(0:4, c(0, 0, 1, -1, 0), from=0, rule=2, type="spline", yleft=.5), -0.214285, tolerance=0.00001) -}) - diff --git a/tests/testthat/testpowermcnemar.R b/tests/testthat/testpowermcnemar.R deleted file mode 100755 index dddb66f..0000000 --- a/tests/testthat/testpowermcnemar.R +++ /dev/null @@ -1,18 +0,0 @@ -context("Test power_mcnemar_test") - - -## -## All of these checks should provide the correct results -## - -test_that("Produces validated results", { - expect_equal(round(power_mcnemar_test(paid=0.05, psi=45/5, power=.8)$n), 22.0) - expect_equal(round(power_mcnemar_test(paid=0.05, psi=45/5, power=.8, alternative="one.sided")$n), 17.0) - expect_equal(round(power_mcnemar_test(144, paid=0.25, psi=45/25, method="exact", alternative="one.sided", sig.level=0.025)$power, 2), 0.80) -}) - - - -#test_that("Checking symmetry of results", { -# expect_equivalent(power_mcnemar_test(paid=0.05, psi=45/5, power=.8), power_mcnemar_test(paid=0.45, psi=5/45, power=.8)) -#})