diff --git a/.Rbuildignore b/.Rbuildignore index 7bf0f61..0de6875 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -16,3 +16,4 @@ ^\.direnv$ ^\.envrc$ ^CRAN-SUBMISSION$ +^\.git-blame-ignore-revs$ diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..e8d0ea8 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Line-ending normalization (CRLF -> LF) +5b72123 + +# Roxygen 8 bump rewritten man/ files with CRLF noise +40cca62 \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/DESCRIPTION b/DESCRIPTION index 9b76c3a..bdddb80 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -31,4 +31,4 @@ Config/testthat/edition: 3 Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) -RoxygenNote: 7.3.3 +RoxygenNote: 8.0.0 diff --git a/R/binomial.R b/R/binomial.R index 7b0ed8e..b825d07 100644 --- a/R/binomial.R +++ b/R/binomial.R @@ -23,8 +23,9 @@ iscambinomnorm <- function(k, n, prob, direction, verbose = TRUE) { on.exit(par(old), add = TRUE) thisx <- 0:n phat <- thisx / n - minx <- max(0, n * prob - 4 * sqrt(prob * (1 - prob) * n)) - maxx <- max(k + 1, min(n, n * prob + 4 * sqrt(prob * (1 - prob) * n))) + binom_limits <- .iscam_binom_limits(n, prob, include_upper = k + 1) + minx <- binom_limits[1] + maxx <- binom_limits[2] myy <- max(dbinom(floor(n * prob), n, prob)) .iscam_plot_discrete_distribution( x = thisx, @@ -126,18 +127,14 @@ iscambinomnorm <- function(k, n, prob, direction, verbose = TRUE) { k1 <- k k2 <- floor(min(normmean - k + normmean, n)) newvalue <- dbinom(k2, size = n, prob) - if (newvalue <= dbinom(k1, size = n, prob) + 0.00001) { - k2 <- k2 - } else { + if (newvalue > dbinom(k1, size = n, prob) + 0.00001) { k2 <- k2 + 1 } } else { k1 <- floor(min(normmean - (k - normmean), n)) k2 <- k newvalue <- dbinom(k1, size = n, prob) - if (newvalue <= dbinom(k, size = n, prob) + 0.00001) { - k1 <- k1 - } else { + if (newvalue > dbinom(k, size = n, prob) + 0.00001) { k1 <- k1 - 1 } } @@ -222,6 +219,113 @@ iscambinomnorm <- function(k, n, prob, direction, verbose = TRUE) { } } +#' Draw the rejection-region shading for a binomial power analysis +#' +#' @param alternative Alternative hypothesis name. +#' @param n Number of trials. +#' @param prob Success probability under the hypothesis. +#' @param minx Left x-limit (in counts). +#' @param maxx Right x-limit (in counts). +#' @param myy Vertical label position. +#' @param color Label and shading color. +#' @param hypothesis_label "Null:" or "Alt:" prefix for messages. +#' @param verbose Logical controlling message output. +#' @param rr Rejection-region cutoff for one-sided alternatives. +#' @param lowerrr Lower cutoff for a two-sided alternative. +#' @param upperrr Upper cutoff for a two-sided alternative. +#' @param message_prob Probability text for the rejection-region message. +#' +#' @return Invisibly `NULL`. +#' +#' @keywords internal +#' @noRd +.iscam_draw_binompower_region <- function( + alternative, + n, + prob, + minx, + maxx, + myy, + color, + hypothesis_label, + verbose, + rr, + lowerrr = NULL, + upperrr = NULL, + message_prob = NULL +) { + if (alternative == "less") { + this.prob <- pbinom(rr, n, prob) + showprob <- format(this.prob, digits = 4) + lines(0:rr, dbinom(0:rr, size = n, prob), col = color, type = "h") + text( + (minx + n * prob) / 2, + myy, + labels = bquote(atop(P(X <= .(rr)), "=" ~ .(showprob))), + pos = 3, + col = color + ) + if (verbose) { + cat(hypothesis_label, "Probability", rr, "and below =", this.prob, "\n") + } + } else if (alternative == "greater") { + this.prob <- 1 - pbinom(rr - 1, n, prob) + showprob <- format(this.prob, digits = 4) + lines(rr:n, dbinom(rr:n, size = n, prob), col = color, type = "h") + text( + (maxx + n * prob) / 2, + myy, + labels = bquote(atop(P(X >= .(rr)), "=" ~ .(showprob))), + pos = 3, + col = color + ) + if (verbose) { + cat(hypothesis_label, "Probability", rr, "and above =", this.prob, "\n") + } + } else if (alternative == "two.sided") { + lowerprob <- pbinom(lowerrr, n, prob) + upperprob <- pbinom(upperrr - 1, n, prob, FALSE) + showlowerprob <- format(lowerprob, digits = 4) + showupperprob <- format(upperprob, digits = 4) + showprob <- format(lowerprob + upperprob, digits = 4) + lines( + 0:lowerrr, + dbinom(0:lowerrr, size = n, prob), + col = color, + type = "h" + ) + lines( + upperrr:n, + dbinom(upperrr:n, size = n, prob), + col = color, + type = "h" + ) + text( + (maxx + n * prob) / 2, + myy, + labels = bquote( + atop( + P(X <= .(lowerrr)) + P(X >= .(upperrr)), + atop("=" ~ .(showlowerprob) + .(showupperprob), "=" ~ .(showprob)) + ) + ), + pos = 3, + col = color + ) + if (verbose) { + cat( + hypothesis_label, + "Probability in rejection region", + if (is.null(message_prob)) showprob else message_prob, + "\n" + ) + } + } else { + stop("Check input for alternative") + } + invisible(NULL) +} + #' Rejection Region for Binomial #' #' `binompower` determines the rejection region corresponding to the level of @@ -275,9 +379,7 @@ iscambinompower <- function( ) ) myy1 <- dbinom(floor(n * prob1), n, prob1) / 2 - old <- par(mfrow = c(2, 1)) - on.exit(par(old), add = TRUE) - old <- par(mar = c(4, 3, 2, 2)) + old <- par(mfrow = c(2, 1), mar = c(4, 3, 2, 2)) on.exit(par(old), add = TRUE) plot( thisx, @@ -295,73 +397,34 @@ iscambinompower <- function( if (alternative == "less") { rr <- qbinom(LOS, n, prob1) - 1 - this.prob1 <- pbinom(rr, n, prob1) - showprob1 <- format(this.prob1, digits = 4) - lines(0:rr, dbinom(0:rr, size = n, prob1), col = "red", type = "h") - text( - (minx + n * prob1) / 2, - myy1, - labels = bquote(atop(P(X <= .(rr)), "=" ~ .(showprob1))), - pos = 3, - col = "red" - ) - if (verbose) { - cat("Null: Probability", rr, "and below =", this.prob1, "\n") - } + lowerrr <- NULL + upperrr <- NULL } else if (alternative == "greater") { rr <- qbinom(LOS, n, prob1, FALSE) + 1 - this.prob1 <- 1 - pbinom(rr - 1, n, prob1) - showprob1 <- format(this.prob1, digits = 4) - lines(rr:n, dbinom(rr:n, size = n, prob1), col = "red", type = "h") - text( - (maxx + n * prob1) / 2, - myy1, - labels = bquote(atop(P(X >= .(rr)), "=" ~ .(showprob1))), - pos = 3, - col = "red" - ) - if (verbose) { - cat("Null: Probability", rr, "and above =", this.prob1, "\n") - } + lowerrr <- NULL + upperrr <- NULL } else if (alternative == "two.sided") { + rr <- NULL lowerrr <- qbinom(LOS / 2, n, prob1) - 1 upperrr <- qbinom(LOS / 2, n, prob1, FALSE) + 1 - lowerprob1 <- pbinom(lowerrr, n, prob1) - upperprob1 <- pbinom(upperrr - 1, n, prob1, FALSE) - showlowerprob1 <- format(lowerprob1, digits = 4) - showupperprob1 <- format(upperprob1, digits = 4) - showprob1 <- format(lowerprob1 + upperprob1, digits = 4) - lines( - 0:lowerrr, - dbinom(0:lowerrr, size = n, prob1), - col = "red", - type = "h" - ) - lines( - upperrr:n, - dbinom(upperrr:n, size = n, prob1), - col = "red", - type = "h" - ) - text( - (maxx + n * prob1) / 2, - myy1, - bquote( - atop( - P(X <= .(lowerrr)) + P(X >= .(upperrr)), - atop("=" ~ .(showlowerprob1) + .(showupperprob1), "=" ~ .(showprob1)) - ) - ), - pos = 3, - col = "red" - ) - if (verbose) { - cat("Null: Probability in rejection region", showprob1, "\n") - } } else { stop("Check input for alternative") } + .iscam_draw_binompower_region( + alternative = alternative, + n = n, + prob = prob1, + minx = minx, + maxx = maxx, + myy = myy1, + color = "red", + hypothesis_label = "Null:", + verbose = verbose, + rr = rr, + lowerrr = lowerrr, + upperrr = upperrr + ) newtitle <- substitute( paste("Binomial (", n == x1, ", ", pi == x2, ") - null", ), list(x1 = n, x2 = prob1) @@ -383,72 +446,31 @@ iscambinompower <- function( mtext(side = 1, line = 2, "Number of Successes") mtext(side = 2, line = 2, "Probability") myy2 <- dbinom(floor(n * prob2), n, prob2) / 2 - if (alternative == "less") { - this.prob2 <- pbinom(rr, n, prob2) - showprob2 <- format(this.prob2, digits = 4) - lines(0:rr, dbinom(0:rr, size = n, prob2), col = "red", type = "h") - text( - (minx + n * prob2) / 2, - myy2, - labels = bquote(atop(P(X <= .(rr)), "=" ~ .(showprob2))), - pos = 3, - col = "red" - ) - if (verbose) { - cat("Alternative: Probability", rr, "and below =", this.prob2, "\n") - } - } else if (alternative == "greater") { - this.prob2 <- 1 - pbinom(rr - 1, n, prob2) - showprob2 <- format(this.prob2, digits = 4) - lines(rr:n, dbinom(rr:n, size = n, prob2), col = "red", type = "h") - text( - (maxx + n * prob2) / 2, - myy2, - labels = bquote(atop(P(X >= .(rr)), "=" ~ .(showprob2))), - pos = 3, - col = "red" - ) - if (verbose) { - cat("Alternative: Probability", rr, "and above =", this.prob2, "\n") - } - } else if (alternative == "two.sided") { - this.prob2 <- pbinom(lowerrr, n, prob2) + - pbinom(upperrr - 1, n, prob2, FALSE) - showprob2 <- format(this.prob2, digits = 4) - lines( - 0:lowerrr, - dbinom(0:lowerrr, size = n, prob2), - col = "red", - type = "h" - ) - lines( - upperrr:n, - dbinom(upperrr:n, size = n, prob2), - col = "red", - type = "h" - ) - text( - (maxx + n * prob2) / 2, - myy1, - labels = bquote(atop( - P(X <= .(lowerrr)) + P(X >= .(upperrr)), - "=" ~ .(showprob2) - )), - pos = 3, - col = "red" - ) - if (verbose) { - cat("Alternative: Probability in rejection region", this.prob2, "\n") + .iscam_draw_binompower_region( + alternative = alternative, + n = n, + prob = prob2, + minx = minx, + maxx = maxx, + myy = myy2, + color = "red", + hypothesis_label = "Alternative:", + verbose = verbose, + rr = rr, + lowerrr = lowerrr, + upperrr = upperrr, + message_prob = if (alternative == "two.sided") { + pbinom(lowerrr, n, prob2) + pbinom(upperrr - 1, n, prob2, FALSE) + } else { + NULL } - } + ) newtitle <- substitute( paste("Binomial (", n == x1, ", ", pi == x2, ") - alternative", ), list(x1 = n, x2 = prob2) ) title(newtitle) } - old <- par(mfrow = c(1, 1)) - on.exit(par(old), add = TRUE) } #' Calculate Binomial Tail Probabilities @@ -481,9 +503,9 @@ iscambinomprob <- function(k, n, prob, lower.tail, verbose = TRUE) { old <- par(mar = c(4, 3, 2, 2)) on.exit(par(old), add = TRUE) thisx <- 0:n - minx <- max(0, n * prob - 4 * sqrt(prob * (1 - prob) * n)) - maxx <- min(n, n * prob + 4 * sqrt(prob * (1 - prob) * n)) - maxx <- max(k + 1, maxx) + binom_limits <- .iscam_binom_limits(n, prob, include_upper = k + 1) + minx <- binom_limits[1] + maxx <- binom_limits[2] myy <- dbinom(floor(n * prob), n, prob) plot( thisx, @@ -508,9 +530,6 @@ iscambinomprob <- function(k, n, prob, lower.tail, verbose = TRUE) { pos = 1, col = "red" ) - if (verbose) { - cat("Probability", k, "and below =", this.prob, "\n") - } } else { this.prob <- 1 - pbinom(k - 1, n, prob) showprob <- format(this.prob, digits = 4) @@ -522,10 +541,8 @@ iscambinomprob <- function(k, n, prob, lower.tail, verbose = TRUE) { pos = 1, col = "red" ) - if (verbose) { - cat("Probability", k, "and above =", this.prob, "\n") - } } + .iscam_print_discrete_tail_probability(verbose, k, this.prob, lower.tail) newtitle <- substitute( paste("Binomial (", n == x1, ", ", pi == x2, ")", ), list(x1 = n, x2 = prob) @@ -598,15 +615,13 @@ iscambinomtest <- function( observed <- .iscam_as_count(observed, n) pvalue <- NULL if (!is.null(hypothesized)) { - minx <- max( - 0, - n * hypothesized - 4 * sqrt(hypothesized * (1 - hypothesized) * n) - ) - maxx <- min( + binom_limits <- .iscam_binom_limits( n, - n * hypothesized + 4 * sqrt(hypothesized * (1 - hypothesized) * n) + hypothesized, + include_upper = observed + 1 ) - maxx <- max(observed + 1, maxx) + minx <- binom_limits[1] + maxx <- binom_limits[2] myy <- max(dbinom(floor(n * hypothesized), n, hypothesized)) * 0.9 x <- 0:n plot( @@ -623,54 +638,18 @@ iscambinomtest <- function( mtext(side = 1, line = 2, "Number of Successes") mtext(side = 2, line = 2, "Probability") - if (alternative == "less") { - pvalue <- pbinom(observed, size = n, prob = hypothesized, TRUE) - lines( - 0:observed, - dbinom(0:observed, size = n, prob = hypothesized), - col = "red", - type = "h", - lwd = 2 - ) - text( - minx, - myy, - labels = paste("p-value:", signif(pvalue, 4)), - pos = 4, - col = "red" - ) - } else if (alternative == "greater") { - pvalue <- pbinom(observed - 1, size = n, prob = hypothesized, FALSE) - lines( - observed:n, - dbinom(observed:n, size = n, prob = hypothesized), - col = "red", - type = "h", - lwd = 2 - ) - text( - maxx, - myy, - labels = paste("p-value:", signif(pvalue, 4)), - pos = 2, - col = "red" - ) - } else { - xvals <- 0:n - probabilities <- dbinom(xvals, size = n, prob = hypothesized) - cutoff <- dbinom(observed, size = n, prob = hypothesized) + 1e-05 - keep <- probabilities <= cutoff - pvalue <- sum(probabilities[keep]) - lines(xvals[keep], probabilities[keep], col = "red", type = "h", lwd = 2) - text( - minx, - myy, - labels = paste("two-sided p-value:\n", signif(pvalue, 4)), - pos = 4, - col = "red" - ) - } - pvalue <- signif(pvalue, 5) + pvalue <- signif( + .iscam_plot_exact_binom_region( + observed = observed, + n = n, + hypothesized = hypothesized, + alternative = alternative, + minx = minx, + maxx = maxx, + myy = myy + ), + 5 + ) abline(h = 0, col = "gray") abline(v = 0, col = "gray") } @@ -678,29 +657,17 @@ iscambinomtest <- function( cat("\nExact Binomial Test\n\n") } statistic <- signif(observed / n, 4) - if (verbose) { - cat(paste( - "Data: observed successes = ", - observed, - ", sample size = ", - n, - ", sample proportion = ", - statistic, - "\n\n", - sep = "" - )) - } + .iscam_print_sample_summary(observed, n, verbose) if (!is.null(hypothesized)) { + .iscam_print_hypotheses( + verbose = verbose, + null_name = "pi", + alt_name = "pi", + hypothesized = hypothesized, + alternative = alternative + ) if (verbose) { - cat(paste("Null hypothesis : pi =", hypothesized, sep = " "), "\n") - } - altname <- switch(alternative, less = "<", greater = ">", two.sided = "<>") - if (verbose) { - cat( - paste("Alternative hypothesis: pi", altname, hypothesized, sep = " "), - "\n" - ) cat(paste("p-value:", pvalue, sep = " "), "\n") } } @@ -709,17 +676,9 @@ iscambinomtest <- function( if (!is.null(conf.level)) { conf.level <- .iscam_normalize_conf_levels(conf.level) for (k in seq_along(conf.level)) { - alpha <- (1 - conf.level[k]) / 2 - lower1[k] <- if (observed == 0) { - 0 - } else { - qbeta(alpha, observed, n - observed + 1) - } - upper1[k] <- if (observed == n) { - 1 - } else { - qbeta(1 - alpha, observed + 1, n - observed) - } + bounds <- .iscam_binom_ci(observed, n, conf.level[k]) + lower1[k] <- bounds[["lower"]] + upper1[k] <- bounds[["upper"]] if (verbose) { CINT <- c(signif(lower1[k], 5), ",", signif(upper1[k], 5)) cat( @@ -747,42 +706,14 @@ iscambinomtest <- function( maxx <- as.integer(min(n, max * n)) if (length(conf.level) == 1) { - myxlab <- .iscam_binom_title(n, signif(lower1[1], 4)) - plot( - seq(minx, maxx), - dbinom(seq(minx, maxx), size = n, prob = lower1[1]), - xlab = " ", - ylab = " ", - type = "h", - xlim = c(minx, maxx) - ) - mtext("Number of successes", side = 1, line = 1.75, adj = 0.5, cex = 0.75) - title(myxlab) - lines( - observed:n, - dbinom(observed:n, size = n, prob = lower1[1]), - col = "red", - type = "h" - ) - - myxlab <- .iscam_binom_title(n, signif(upper1[1], 4)) - plot( - seq(minx, maxx), - dbinom(seq(minx, maxx), size = n, prob = upper1[1]), - xlab = " ", - ylab = " ", - type = "h", - xlim = c(minx, maxx) - ) - lines( - 0:observed, - dbinom(0:observed, size = n, prob = upper1[1]), - col = "red", - type = "h" + .iscam_plot_ci_binom_panels( + n = n, + observed = observed, + minx = minx, + maxx = maxx, + lower = lower1[1], + upper = upper1[1] ) - - mtext("Number of successes", side = 1, line = 1.75, adj = 0.5, cex = 0.75) - title(myxlab) } for (k in seq_along(conf.level)) { @@ -798,8 +729,6 @@ iscambinomtest <- function( } } - old <- par(mfrow = c(1, 1)) - on.exit(par(old), add = TRUE) invisible(list("pvalue" = pvalue, "lower" = lower1, "upper" = upper1)) } @@ -829,8 +758,9 @@ iscaminvbinom <- function(alpha, n, prob, lower.tail, verbose = TRUE) { on.exit(par(old), add = TRUE) thisx <- 0:n - minx <- max(0, n * prob - 4 * sqrt(prob * (1 - prob) * n)) - maxx <- min(n, n * prob + 4 * sqrt(prob * (1 - prob) * n)) + binom_limits <- .iscam_binom_limits(n, prob) + minx <- binom_limits[1] + maxx <- binom_limits[2] myy <- dbinom(floor(n * prob), n, prob) / 2 plot( thisx, @@ -876,7 +806,6 @@ iscaminvbinom <- function(alpha, n, prob, lower.tail, verbose = TRUE) { col = "red", pos = 4 ) - # text(answer, dbinom(answer, size=n, prob), labels=actualprob, pos=2, col="red") text( answer, dbinom(answer, size = n, prob), @@ -919,7 +848,6 @@ iscaminvbinom <- function(alpha, n, prob, lower.tail, verbose = TRUE) { ), col = "red" ) - # text(answer, dbinom(answer, size=n, prob), labels=actualprob, pos=2, col="red") text( answer, dbinom(answer, n, prob), diff --git a/R/hypergeometric.R b/R/hypergeometric.R index 352e0e5..9f05779 100644 --- a/R/hypergeometric.R +++ b/R/hypergeometric.R @@ -24,9 +24,7 @@ iscamhypernorm <- function(k, total, succ, n, lower.tail, verbose = TRUE) { old <- par(mar = c(4, 4, 2, 1)) on.exit(par(old), add = TRUE) - if (k < 1) { - k <- round((k * n * (total - n) + n * succ) / total) - } + k <- .iscam_hyper_k_to_count(k, total, succ, n) fail <- total - succ thisx <- max(0, n - fail):min(n, succ) @@ -190,9 +188,7 @@ iscamhyperprob <- function(k, total, succ, n, lower.tail, verbose = TRUE) { old <- par(mar = c(4, 4, 2, 1)) on.exit(par(old), add = TRUE) - if (k < 1 && k > 0) { - k <- round((k * (total - n) * n + succ * n) / total) - } + k <- .iscam_hyper_k_to_count(k, total, succ, n) fail <- total - succ thisx <- max(0, n - fail):min(n, succ) diff --git a/R/normal.R b/R/normal.R index 5e610bb..c63fc4a 100644 --- a/R/normal.R +++ b/R/normal.R @@ -360,6 +360,126 @@ iscaminvnorm <- function( } } +#' Draw the rejection-region shading for a normal power analysis +#' +#' @param alternative Alternative hypothesis name. +#' @param LOS Level of significance. +#' @param mean Distribution mean under the hypothesis. +#' @param std Distribution standard deviation. +#' @param minx Left plotting bound. +#' @param maxx Right plotting bound. +#' @param myy1 Vertical label position. +#' @param color Label and shading color. +#' @param hypothesis_label "Null:" or "Alt:" prefix for messages. +#' @param verbose Logical controlling message output. +#' @param two_sided_label_x X-position of the two-sided label. +#' +#' @return Invisibly `NULL`. +#' +#' @keywords internal +#' @noRd +.iscam_draw_normpower_region <- function( + alternative, + LOS, + mean, + std, + minx, + maxx, + myy1, + color, + hypothesis_label, + verbose, + rr, + lowerrr = NULL, + upperrr = NULL, + two_sided_label_x = (maxx + mean) / 2 +) { + if (alternative == "less") { + this.prob <- pnorm(rr, mean, std) + showprob <- format(this.prob, digits = 4) + drawseq <- seq(minx, rr, 0.001) + polygon( + c(drawseq, rr, minx), + c(dnorm(drawseq, mean, std), 0, 0), + col = color + ) + rr <- format(rr, digits = 4) + text( + minx, + myy1, + labels = bquote(atop(P(hat(p) <= .(rr)), "=" ~ .(showprob))), + pos = 4, + col = color + ) + if (verbose) { + cat(hypothesis_label, "Probability", rr, "and below =", this.prob, "\n") + } + } else if (alternative == "greater") { + this.prob <- 1 - pnorm(rr, mean, std) + showprob <- format(this.prob, digits = 4) + drawseq <- seq(rr, maxx, 0.001) + polygon( + c(drawseq, maxx, rr), + c(dnorm(drawseq, mean, std), 0, 0), + col = color + ) + rr <- format(rr, digits = 4) + text( + maxx, + myy1, + labels = bquote(atop(P(hat(p) >= .(rr)), "=" ~ .(showprob))), + pos = 2, + col = color + ) + if (verbose) { + cat(hypothesis_label, "Probability", rr, "and above =", this.prob, "\n") + } + } else if (alternative == "two.sided") { + lowerprob <- pnorm(lowerrr, mean, std) + upperprob <- pnorm(upperrr, mean, std, FALSE) + showlowerprob <- format(lowerprob, digits = 4) + showupperprob <- format(upperprob, digits = 4) + showprob <- format(lowerprob + upperprob, digits = 4) + drawseq <- seq(minx, lowerrr, 0.001) + polygon( + c(drawseq, lowerrr, minx), + c(dnorm(drawseq, mean, std), 0, 0), + col = color + ) + drawseq <- seq(upperrr, maxx, 0.001) + polygon( + c(drawseq, maxx, upperrr), + c(dnorm(drawseq, mean, std), 0, 0), + col = color + ) + showupperrr <- format(upperrr, digits = 4) + showlowerrr <- format(lowerrr, digits = 4) + text( + two_sided_label_x, + myy1, + labels = bquote( + atop( + P(hat(p) <= .(showlowerrr)) + P(hat(p) >= .(showupperrr)), + atop("=" ~ .(showlowerprob) + .(showupperprob), "=" ~ .(showprob)) + ) + ), + pos = 3, + col = color + ) + if (verbose) { + cat( + hypothesis_label, + "Probability in rejection region", + showprob, + "\n" + ) + } + } else { + stop("Check input for alternative") + } + invisible(NULL) +} + #' Rejection Region for Normal #' #' `normpower` determines the rejection region corresponding to the level of @@ -417,88 +537,36 @@ iscamnormpower <- function(LOS, n, prob1, alternative, prob2, verbose = TRUE) { if (alternative == "less") { rr <- qnorm(LOS, mean, std) - this.prob1 <- pnorm(rr, mean, std) - showprob1 <- format(this.prob1, digits = 4) - drawseq <- seq(minx, rr, 0.001) - polygon( - c(drawseq, rr, minx), - c(dnorm(drawseq, mean, std), 0, 0), - col = "red" - ) - rr <- format(rr, digits = 4) - text( - minx, - myy1, - labels = bquote(atop(P(hat(p) <= .(rr)), "=" ~ .(showprob1))), - pos = 4, - col = "red" - ) - if (verbose) { - cat("Null: Probability", rr, "and below =", this.prob1, "\n") - } + lowerrr <- NULL + upperrr <- NULL } else if (alternative == "greater") { rr <- qnorm(LOS, mean, std, FALSE) - this.prob1 <- 1 - pnorm(rr, mean, std) - - showprob1 <- format(this.prob1, digits = 4) - drawseq <- seq(rr, maxx, 0.001) - polygon( - c(drawseq, maxx, rr), - c(dnorm(drawseq, mean, std), 0, 0), - col = "red" - ) - rr <- format(rr, digits = 4) - text( - maxx, - myy1, - labels = bquote(atop(P(hat(p) >= .(rr)), "=" ~ .(showprob1))), - pos = 2, - col = "red" - ) - if (verbose) { - cat("Null: Probability", rr, "and above =", this.prob1, "\n") - } + lowerrr <- NULL + upperrr <- NULL } else if (alternative == "two.sided") { + rr <- NULL lowerrr <- qnorm(LOS / 2, mean, std) upperrr <- qnorm(LOS / 2, mean, std, FALSE) - lowerprob1 <- pnorm(lowerrr, mean, std) - upperprob1 <- pnorm(upperrr, mean, std, FALSE) - showlowerprob1 <- format(lowerprob1, digits = 4) - showupperprob1 <- format(upperprob1, digits = 4) - showprob1 <- format(lowerprob1 + upperprob1, digits = 4) - drawseq <- seq(minx, lowerrr, 0.001) - polygon( - c(drawseq, lowerrr, minx), - c(dnorm(drawseq, mean, std), 0, 0), - col = "red" - ) - drawseq <- seq(upperrr, maxx, 0.001) - polygon( - c(drawseq, maxx, upperrr), - c(dnorm(drawseq, mean, std), 0, 0), - col = "red" - ) - showupperrr <- format(upperrr, digits = 4) - showlowerrr <- format(lowerrr, digits = 4) - text( - (maxx + prob1) / 2, - myy1, - labels = bquote( - atop( - P(hat(p) <= .(showlowerrr)) + P(hat(p) >= .(showupperrr)), - atop("=" ~ .(showlowerprob1) + .(showupperprob1), "=" ~ .(showprob1)) - ) - ), - pos = 3, - col = "red" - ) - if (verbose) { - cat("Null: Probability in rejection region", showprob1, "\n") - } } else { stop("Check input for alternative") } + .iscam_draw_normpower_region( + alternative = alternative, + LOS = LOS, + mean = mean, + std = std, + minx = minx, + maxx = maxx, + myy1 = myy1, + color = "red", + hypothesis_label = "Null:", + verbose = verbose, + rr = rr, + lowerrr = lowerrr, + upperrr = upperrr + ) + title( substitute( paste("Null: Normal (", mu == x1, ", ", sigma == x2, ")", ), @@ -519,93 +587,26 @@ iscamnormpower <- function(LOS, n, prob1, alternative, prob2, verbose = TRUE) { panel.first = grid() ) - if (alternative == "less") { - rr <- qnorm(LOS, mean, std) - this.prob2 <- pnorm(rr, mean2, std2) - showprob2 <- format(this.prob2, digits = 4) - drawseq <- seq(minx, rr, 0.001) - polygon( - c(drawseq, rr, minx), - c(dnorm(drawseq, mean2, std2), 0, 0), - col = "blue" - ) - rr <- format(rr, digits = 4) - text( - minx, - myy1, - labels = bquote(atop(P(hat(p) <= .(rr)), "=" ~ .(showprob2))), - pos = 4, - col = "blue" - ) - if (verbose) { - cat("Alt: Probability", rr, "and below =", this.prob2, "\n") - } - } else if (alternative == "greater") { - rr <- qnorm(LOS, mean, std, FALSE) - this.prob2 <- 1 - pnorm(rr, mean2, std2) - showprob2 <- format(this.prob2, digits = 4) - drawseq <- seq(rr, maxx, 0.001) - polygon( - c(drawseq, maxx, rr), - c(dnorm(drawseq, mean2, std2), 0, 0), - col = "blue" - ) - rr <- format(rr, digits = 4) - text( - maxx, - myy1, - labels = bquote(atop(P(hat(p) >= .(rr)), "=" ~ .(showprob2))), - pos = 2, - col = "blue" - ) - if (verbose) { - cat("Alt: Probability", rr, "and above =", this.prob2, "\n") - } - } else if (alternative == "two.sided") { - lowerrr <- qnorm(LOS / 2, mean, std) - upperrr <- qnorm(LOS / 2, mean, std, FALSE) - lowerprob2 <- pnorm(lowerrr, mean2, std2) - upperprob2 <- pnorm(upperrr, mean2, std2, FALSE) - showlowerprob2 <- format(lowerprob2, digits = 4) - showupperprob2 <- format(upperprob2, digits = 4) - showprob2 <- format(lowerprob2 + upperprob2, digits = 4) - drawseq <- seq(minx, lowerrr, 0.001) - polygon( - c(drawseq, lowerrr, minx), - c(dnorm(drawseq, mean2, std2), 0, 0), - col = "blue" - ) - drawseq <- seq(upperrr, maxx, 0.001) - polygon( - c(drawseq, maxx, upperrr), - c(dnorm(drawseq, mean2, std2), 0, 0), - col = "blue" - ) - showupperrr <- format(upperrr, digits = 4) - showlowerrr <- format(lowerrr, digits = 4) - text2 <- (maxx + prob2) / 2 - if (prob1 < prob2) { - text2 <- (minx + prob1) / 2 - } - text( - text2, - myy1, - labels = bquote( - atop( - P(hat(p) <= .(showlowerrr)) + P(hat(p) >= .(showupperrr)), - atop( - "=" ~ .(showlowerprob2) + .(showupperprob2), - "=" ~ .(showprob2) - ) - ) - ), - pos = 3, - col = "blue" - ) - if (verbose) { - cat("Alt: Probability in rejection region", showprob2, "\n") - } + text2 <- (maxx + prob2) / 2 + if (prob1 < prob2) { + text2 <- (minx + prob1) / 2 } + .iscam_draw_normpower_region( + alternative = alternative, + LOS = LOS, + mean = mean2, + std = std2, + minx = minx, + maxx = maxx, + myy1 = myy1, + color = "blue", + hypothesis_label = "Alt:", + verbose = verbose, + rr = rr, + lowerrr = lowerrr, + upperrr = upperrr, + two_sided_label_x = text2 + ) title( substitute( @@ -615,8 +616,6 @@ iscamnormpower <- function(LOS, n, prob1, alternative, prob2, verbose = TRUE) { ) } - old <- par(mfrow = c(1, 1)) - on.exit(par(old), add = TRUE) } #' One Proportion Z-Test and Interval @@ -673,37 +672,17 @@ iscamonepropztest <- function( cat("\nOne Proportion z test\n\n") } statistic <- signif(observed / n, 4) - if (verbose) { - cat(paste( - "Data: observed successes = ", - observed, - ", sample size = ", - n, - ", sample proportion = ", - statistic, - "\n\n", - sep = "" - )) - } + .iscam_print_sample_summary(observed, n, verbose) zvalue <- NULL pvalue <- NULL if (!is.null(hypothesized)) { - if (verbose) { - cat(paste("Null hypothesis : pi =", hypothesized, sep = " "), "\n") - } - altname <- switch( - alternative, - less = "<", - greater = ">", - two.sided = "<>", - not.equal = "<>" + .iscam_print_hypotheses( + verbose = verbose, + null_name = "pi", + alt_name = "pi", + hypothesized = hypothesized, + alternative = alternative ) - if (verbose) { - cat( - paste("Alternative hypothesis: pi", altname, hypothesized, sep = " "), - "\n" - ) - } zvalue <- (statistic - hypothesized) / sqrt(hypothesized * (1 - hypothesized) / n) if (verbose) { @@ -755,83 +734,49 @@ iscamonepropztest <- function( mtext(side = 1, line = 3, bquote("<-" ~ "Sample Proportions" ~ "->")) mtext(side = 2, line = 2, "Density") if (alternative == "less") { - drawseq <- seq(min, statistic, 0.001) - polygon( - c(drawseq, statistic, min), - c(dnorm(drawseq, hypothesized, SD), 0, 0), - col = "red" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.9, - labels = paste("z-statistic:", signif(zvalue, 4)), - pos = 4, - col = "blue" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.8, - labels = paste("p-value:", pvalue), - pos = 4, - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = min, + max_x = max, + statistic = statistic, + density_fn = function(v) dnorm(v, hypothesized, SD), + step_fn = function(a, b) 0.001, + statistic_label = "z-statistic:", + statistic_value = signif(zvalue, 4), + pvalue_label = "p-value:", + pvalue_text = pvalue ) } else if (alternative == "greater") { - drawseq <- seq(statistic, max, 0.001) - polygon( - c(statistic, drawseq, max), - c(0, dnorm(drawseq, hypothesized, SD), 0), - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = min, + max_x = max, + statistic = statistic, + density_fn = function(v) dnorm(v, hypothesized, SD), + step_fn = function(a, b) 0.001, + statistic_label = "z-statistic:", + statistic_value = signif(zvalue, 4), + pvalue_label = "p-value:", + pvalue_text = pvalue ) - text( - max, - max(dnorm(hypothesized, hypothesized, SD)) * 0.9, - labels = paste("z-statistic:", signif(zvalue, 4)), - pos = 2, - col = "blue" - ) - text( - max, - max(dnorm(hypothesized, hypothesized, SD)) * 0.8, - labels = paste("p-value:", pvalue), - pos = 2, - col = "red" - ) - } else if (alternative == "two.sided" || alternative == "not.equal") { - if (statistic < hypothesized) { - drawseq1 <- seq(min, statistic, 0.001) - drawseq2 <- seq(hypothesized + (hypothesized - statistic), max, 0.001) - } else { - drawseq1 <- seq(min, hypothesized - (statistic - hypothesized), 0.001) - drawseq2 <- seq(statistic, max, 0.001) - } - polygon( - c(min, drawseq1, drawseq1[length(drawseq1)]), - c(0, dnorm(drawseq1, hypothesized, SD), 0), - col = "red" - ) - polygon( - c(drawseq2[1], drawseq2, max), - c(0, dnorm(drawseq2, hypothesized, SD), 0), - col = "red" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.9, - labels = paste("z-statistic:", signif(zvalue, 4)), - pos = 4, - col = "blue" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.8, - labels = paste("two-sided p-value:", pvalue), - pos = 4, - col = "red" + } else if (.iscam_is_two_sided_alt(alternative)) { + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = min, + max_x = max, + statistic = statistic, + density_fn = function(v) dnorm(v, hypothesized, SD), + step_fn = function(a, b) 0.001, + statistic_label = "z-statistic:", + statistic_value = signif(zvalue, 4), + pvalue_label = "two-sided p-value:", + pvalue_text = pvalue ) } } - old <- par(mfrow = c(3, 1)) - on.exit(par(old), add = TRUE) if (length(conf.level) > 1) { old <- par(mar = c(4, 2, 1.5, 4), mfrow = c(length(conf.level), 1)) on.exit(par(old), add = TRUE) @@ -862,62 +807,26 @@ iscamonepropztest <- function( SDphat <- sqrt(statistic * (1 - statistic) / n) min <- statistic - 4 * SDphat max <- statistic + 4 * SDphat - CIseq <- seq(min, max, 0.001) if (length(conf.level) == 1) { - myxlab <- substitute( - paste("Normal (", mean == x1, ", ", SD == x2, ")", ), - list(x1 = signif(lower[1], 4), x2 = signif(SDphat, 4)) - ) - plot(CIseq, dnorm(CIseq, lower[1], SDphat), type = "l", xlab = " ") - mtext( - "sample proportions", - side = 1, - line = 1.75, - adj = 0.5, - cex = 0.75 - ) - topseq <- seq(statistic, max, 0.001) - polygon( - c(statistic, topseq, max), - c(0, dnorm(topseq, lower[1], SDphat), 0), - col = "red" - ) - title(myxlab) - myxlab <- substitute( - paste("Normal (", mean == x1, ", ", SD == x2, ")", ), - list(x1 = signif(upper[1], 4), x2 = signif(SDphat, 4)) - ) - upper_curve <- seq(min, max, 0.001) - plot( - upper_curve, - dnorm(upper_curve, upper[1], SDphat), - type = "l", - xlab = " " - ) - mtext( - "sample proportions", - side = 1, - line = 1.75, - adj = 0.5, - cex = 0.75 - ) - bottomseq <- seq(min, statistic, 0.001) - polygon( - c(min, bottomseq, statistic, statistic), - c( - 0, - dnorm(bottomseq, upper[1], SDphat), - dnorm(statistic, upper[1], SDphat), - 0 + .iscam_plot_ci_bounds_curves( + min_x = min, + max_x = max, + statistic = statistic, + lower = lower[1], + upper = upper[1], + curve_sd = SDphat, + lower_title = substitute( + paste("Normal (", mean == x1, ", ", SD == x2, ")", ), + list(x1 = signif(lower[1], 4), x2 = signif(SDphat, 4)) ), - col = "red" - ) - newtitle <- substitute( - paste("Normal (", mean == x1, ", ", SD == x2, ")", ), - list(x1 = signif(upper[1], 4), x2 = signif(SDphat, 4)) + upper_title = substitute( + paste("Normal (", mean == x1, ", ", SD == x2, ")", ), + list(x1 = signif(upper[1], 4), x2 = signif(SDphat, 4)) + ), + margin_label = "sample proportions", + step_fn = function(a, b) 0.001 ) - title(newtitle) } for (k in seq_along(conf.level)) { .iscam_plot_ci_strip( @@ -1047,37 +956,19 @@ iscamtwopropztest <- function( )) } if (!is.null(alternative)) { - if (verbose) { - cat( - paste("Null hypothesis : pi1-pi2 =", hypothesized, sep = " "), - "\n" - ) - } - altname <- switch( - alternative, - less = "<", - greater = ">", - two.sided = "<>", - not.equal = "<>" + .iscam_print_hypotheses( + verbose = verbose, + null_name = "pi1-pi2", + alt_name = "pi1-pi2", + hypothesized = hypothesized, + alternative = alternative ) - if (verbose) { - cat( - paste( - "Alternative hypothesis: pi1-pi2", - altname, - hypothesized, - sep = " " - ), - "\n" - ) - } pooledphat <- (observed1 + observed2) / (n1 + n2) zvalue <- (statistic1 - statistic2 - hypothesized) / sqrt(pooledphat * (1 - pooledphat) * (1 / n1 + 1 / n2)) if (verbose) { cat("z-statistic:", signif(zvalue, 4), "\n") } - pvalue <- 2 SD <- sqrt(pooledphat * (1 - pooledphat) * (1 / n1 + 1 / n2)) min <- min(hypothesized - 4 * SD, hypothesized - abs(zvalue) * SD - 0.001) max <- max(hypothesized + 4 * SD, hypothesized + abs(zvalue) * SD + 0.001) @@ -1120,80 +1011,48 @@ iscamtwopropztest <- function( if (alternative == "less") { pvalue <- signif(pnorm(zvalue), 4) - drawseq <- seq(min, statistic, 0.001) - polygon( - c(drawseq, statistic, min), - c(dnorm(drawseq, hypothesized, SD), 0, 0), - col = "red" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.9, - labels = paste("z-statistic:", signif(zvalue, 4)), - pos = 4, - col = "blue" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.8, - labels = paste("p-value:", pvalue), - pos = 4, - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = min, + max_x = max, + statistic = statistic, + density_fn = function(v) dnorm(v, hypothesized, SD), + step_fn = function(a, b) 0.001, + statistic_label = "z-statistic:", + statistic_value = signif(zvalue, 4), + pvalue_label = "p-value:", + pvalue_text = pvalue ) } else if (alternative == "greater") { pvalue <- signif(1 - pnorm(zvalue), 4) - drawseq <- seq(statistic, max, 0.001) - polygon( - c(statistic, drawseq, max), - c(0, dnorm(drawseq, hypothesized, SD), 0), - col = "red" - ) - text( - max, - max(dnorm(hypothesized, hypothesized, SD)) * 0.9, - labels = paste("z-statistic:", signif(zvalue, 4)), - pos = 2, - col = "blue" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = min, + max_x = max, + statistic = statistic, + density_fn = function(v) dnorm(v, hypothesized, SD), + step_fn = function(a, b) 0.001, + statistic_label = "z-statistic:", + statistic_value = signif(zvalue, 4), + pvalue_label = "p-value:", + pvalue_text = pvalue ) - text( - max, - max(dnorm(hypothesized, hypothesized, SD)) * 0.8, - labels = paste("p-value:", pvalue), - pos = 2, - col = "red" - ) - } else if (alternative == "two.sided" || alternative == "not.equal") { + } else if (.iscam_is_two_sided_alt(alternative)) { pvalue <- signif(2 * pnorm(-1 * abs(zvalue)), 4) - if (statistic < hypothesized) { - drawseq1 <- seq(min, statistic, 0.001) - drawseq2 <- seq(hypothesized + (hypothesized - statistic), max, 0.001) - } else { - drawseq1 <- seq(min, hypothesized - (statistic - hypothesized), 0.001) - drawseq2 <- seq(statistic, max, 0.001) - } - polygon( - c(min, drawseq1, drawseq1[length(drawseq1)]), - c(0, dnorm(drawseq1, hypothesized, SD), 0), - col = "red" - ) - polygon( - c(drawseq2[1], drawseq2, max), - c(0, dnorm(drawseq2, hypothesized, SD), 0), - col = "red" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.9, - labels = paste("z-statistic:", signif(zvalue, 4)), - pos = 4, - col = "blue" - ) - text( - min, - max(dnorm(hypothesized, hypothesized, SD)) * 0.8, - labels = paste("two-sided p-value:", pvalue), - pos = 4, - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = min, + max_x = max, + statistic = statistic, + density_fn = function(v) dnorm(v, hypothesized, SD), + step_fn = function(a, b) 0.001, + statistic_label = "z-statistic:", + statistic_value = signif(zvalue, 4), + pvalue_label = "two-sided p-value:", + pvalue_text = pvalue ) } } #end have alternative @@ -1206,7 +1065,6 @@ iscamtwopropztest <- function( on.exit(par(old), add = TRUE) } for (k in seq_along(conf.level)) { - #myout=prop.test(observed, n, p=statistic, alternative="two.sided", conf.level, correct=FALSE) criticalvalue <- qnorm((1 - conf.level[k]) / 2) sephat <- sqrt( statistic1 * @@ -1231,63 +1089,27 @@ iscamtwopropztest <- function( if (is.null(alternative)) { min <- statistic - 4 * sephat max <- statistic + 4 * sephat - CIseq <- seq(min, max, 0.001) if (length(conf.level) == 1) { old <- par(mar = c(4, 0.5, 1.5, 0.5), mfrow = c(3, 1)) on.exit(par(old), add = TRUE) - myxlab <- substitute( - paste("Normal (", mean == x1, ", ", SD == x2, ")", ), - list(x1 = signif(lower[1], 4), x2 = signif(sephat, 4)) - ) - plot(CIseq, dnorm(CIseq, lower[1], sephat), type = "l", xlab = " ") - mtext( - "difference in sample proportions", - side = 1, - line = 1.75, - adj = 0.5, - cex = 0.75 - ) - topseq <- seq(statistic, max, 0.001) - polygon( - c(statistic, topseq, max), - c(0, dnorm(topseq, lower[1], sephat), 0), - col = "red" - ) - title(myxlab) - myxlab <- substitute( - paste("Normal (", mean == x1, ", ", SD == x2, ")", ), - list(x1 = signif(upper[1], 4), x2 = signif(sephat, 4)) - ) - upper_curve <- seq(min, max, 0.001) - plot( - upper_curve, - dnorm(upper_curve, upper[1], sephat), - type = "l", - xlab = " " - ) - mtext( - "difference in sample proportions", - side = 1, - line = 1.75, - adj = 0.5, - cex = 0.75 - ) - bottomseq <- seq(min, statistic, 0.001) - polygon( - c(min, bottomseq, statistic, statistic), - c( - 0, - dnorm(bottomseq, upper[1], sephat), - dnorm(statistic, upper[1], sephat), - 0 + .iscam_plot_ci_bounds_curves( + min_x = min, + max_x = max, + statistic = statistic, + lower = lower[1], + upper = upper[1], + curve_sd = sephat, + lower_title = substitute( + paste("Normal (", mean == x1, ", ", SD == x2, ")", ), + list(x1 = signif(lower[1], 4), x2 = signif(sephat, 4)) ), - col = "red" - ) - newtitle <- substitute( - paste("Normal (", mean == x1, ", ", SD == x2, ")", ), - list(x1 = signif(upper, 4), x2 = signif(sephat, 4)) + upper_title = substitute( + paste("Normal (", mean == x1, ", ", SD == x2, ")", ), + list(x1 = signif(upper, 4), x2 = signif(sephat, 4)) + ), + margin_label = "difference in sample proportions", + step_fn = function(a, b) 0.001 ) - title(newtitle) } # end one interval for (k in seq_along(conf.level)) { .iscam_plot_ci_strip( @@ -1308,8 +1130,6 @@ iscamtwopropztest <- function( cat("p-value:", pvalue, "\n") } } - old <- par(mfrow = c(1, 1)) - on.exit(par(old), add = TRUE) invisible(list( "zvalue" = zvalue, "pvalue" = pvalue, diff --git a/R/overlayDensities.R b/R/overlayDensities.R index 6750a9e..7f22ac6 100644 --- a/R/overlayDensities.R +++ b/R/overlayDensities.R @@ -6,7 +6,7 @@ #' @param bins (optional) number of bins for the histogram. #' #' @keywords internal -#' @name .add_density_common_params +#' @name .iscam_add_density_common_params NULL #' Overlay an Exponential Density Function on Histogram @@ -14,7 +14,7 @@ NULL #' `addexp` creates a histogram of `x` and overlays an exponential density #' function with \eqn{\lambda = \frac{1}{mean}}. #' -#' @inheritParams .add_density_common_params +#' @inheritParams .iscam_add_density_common_params #' @returns A histogram of x overlayed with an exponential density function. #' #' @export @@ -34,7 +34,7 @@ iscamaddexp <- function( return(invisible()) } - .internal_add_density( + .iscam_add_density( x, fun1 = function(z) dexp(z, 1 / mean(x, na.rm = TRUE)), label1 = "exponential", @@ -49,7 +49,7 @@ iscamaddexp <- function( #' #' `addlnorm` creates a histogram of `x` and overlays a log normal density function. #' -#' @inheritParams .add_density_common_params +#' @inheritParams .iscam_add_density_common_params #' #' @returns A histogram of x overlayed with an log normal density function. #' @@ -73,7 +73,7 @@ iscamaddlnorm <- function( mu <- mean(log(x), na.rm = TRUE) sdx <- sd(log(x), na.rm = TRUE) - .internal_add_density( + .iscam_add_density( x, fun1 = function(z) dlnorm(z, mu, sdx), label1 = "log-normal", @@ -88,7 +88,7 @@ iscamaddlnorm <- function( #' #' `addnorm` creates a histogram of `x` and overlays a normal density function. #' -#' @inheritParams .add_density_common_params +#' @inheritParams .iscam_add_density_common_params #' #' @returns A histogram of x overlayed with an normal density function. #' @@ -112,7 +112,7 @@ iscamaddnorm <- function( mu <- mean(x, na.rm = TRUE) sdx <- sd(x, na.rm = TRUE) - .internal_add_density( + .iscam_add_density( x, fun1 = function(z) dnorm(z, mu, sdx), label1 = "normal", @@ -126,7 +126,7 @@ iscamaddnorm <- function( #' Overlay a t Density Function on Histogram #' -#' @inheritParams .add_density_common_params +#' @inheritParams .iscam_add_density_common_params #' @param df A numeric value representing the degrees of freedom of `x`. #' #' @returns A histogram of x overlayed with an t density function. @@ -152,7 +152,7 @@ iscamaddt <- function( mu <- mean(x, na.rm = TRUE) sdx <- sd(x, na.rm = TRUE) - .internal_add_density( + .iscam_add_density( x, fun1 = function(z) dt((z - mu) / sdx, df) / sdx, label1 = paste0("t, df=", df), @@ -166,7 +166,7 @@ iscamaddt <- function( #' Overlay a t Density Function and a Normal Density Function on Histogram #' -#' @inheritParams .add_density_common_params +#' @inheritParams .iscam_add_density_common_params #' @param df A numeric value representing the degrees of freedom of `x`. #' #' @returns A histogram of x overlayed with an t density function and a normal density function. @@ -192,7 +192,7 @@ iscamaddtnorm <- function( mu <- mean(x, na.rm = TRUE) sdx <- sd(x, na.rm = TRUE) - .internal_add_density( + .iscam_add_density( x, fun1 = function(z) dnorm((z - mu) / sdx) / sdx, col1 = 3, @@ -235,7 +235,7 @@ iscamaddtnorm <- function( #' #' @noRd #' @keywords internal -.internal_add_density <- function( +.iscam_add_density <- function( x, fun1, col1 = 2, diff --git a/R/plots.R b/R/plots.R index d661736..b76f761 100644 --- a/R/plots.R +++ b/R/plots.R @@ -7,7 +7,7 @@ #' @param ylab (optional) y-axis label for the plot. Only displayed when `explanatory` is provided. #' #' @keywords internal -#' @name .plot_funcs_common_params +#' @name .iscam_plot_funcs_common_params NULL #' A box plot @@ -15,7 +15,7 @@ NULL #' `boxplot` plots the given data in a box plot. If a second categorical variable #' is given, the data is grouped by this variable. #' -#' @inheritParams .plot_funcs_common_params +#' @inheritParams .iscam_plot_funcs_common_params #' #' @return A box plot. #' @@ -75,7 +75,7 @@ iscamboxplot <- function( #' given, the data is grouped by this variable. Use `names` & `mytitle` to #' specify the labels and title. #' -#' @inheritParams .plot_funcs_common_params +#' @inheritParams .iscam_plot_funcs_common_params #' #' @return A dot plot. #' @@ -140,3 +140,239 @@ iscamdotplot <- function( } invisible() } + +#' Draw the shaded region and annotations for a hypothesis-test plot +#' +#' Handles the "less", "greater", and two-sided alternative branches used by +#' the one/two-sample t and z test plots. +#' +#' @param alternative Alternative hypothesis name. +#' @param center Null value the distribution is centered on. +#' @param min_x Left plotting bound. +#' @param max_x Right plotting bound. +#' @param statistic Observed statistic. +#' @param density_fn Function returning density values for x-coordinates. +#' @param step_fn Function of two bounds returning the sequence step size. +#' @param statistic_label Label prefix for the observed statistic. +#' @param statistic_value Formatted statistic for the label. +#' @param pvalue_label Label prefix for the p-value. +#' @param pvalue_text Formatted p-value for the label. +#' +#' @return Invisibly `NULL`. +#' +#' @keywords internal +#' @noRd +.iscam_draw_test_region <- function( + alternative, + center, + min_x, + max_x, + statistic, + density_fn, + step_fn, + statistic_label, + statistic_value, + pvalue_label, + pvalue_text +) { + max_y <- density_fn(center) + if (alternative == "less") { + drawseq <- seq(min_x, statistic, by = step_fn(min_x, statistic)) + polygon( + c(drawseq, statistic, min_x), + c(0, density_fn(drawseq), 0), + col = "red" + ) + text( + min_x, + max_y * 0.9, + labels = paste(statistic_label, statistic_value), + pos = 4, + col = "blue" + ) + text( + min_x, + max_y * 0.8, + labels = paste(pvalue_label, pvalue_text), + pos = 4, + col = "red" + ) + return(invisible(NULL)) + } + if (alternative == "greater") { + drawseq <- seq(statistic, max_x, by = step_fn(statistic, max_x)) + polygon( + c(statistic, drawseq, max_x), + c(0, density_fn(drawseq), 0), + col = "red" + ) + text( + max_x, + max_y * 0.9, + labels = paste(statistic_label, statistic_value), + pos = 2, + col = "blue" + ) + text( + max_x, + max_y * 0.8, + labels = paste(pvalue_label, pvalue_text), + pos = 2, + col = "red" + ) + return(invisible(NULL)) + } + if (.iscam_is_two_sided_alt(alternative)) { + drawseq <- .iscam_two_sided_draw_sequences( + min_x = min_x, + max_x = max_x, + center = center, + statistic = statistic + ) + polygon( + c(min_x, drawseq$left, drawseq$left[length(drawseq$left)]), + c(0, density_fn(drawseq$left), 0), + col = "red" + ) + polygon( + c(drawseq$right[1], drawseq$right, max_x), + c(0, density_fn(drawseq$right), 0), + col = "red" + ) + text( + min_x, + max_y * 0.9, + labels = paste(statistic_label, statistic_value), + pos = 4, + col = "blue" + ) + text( + min_x, + max_y * 0.8, + labels = paste(pvalue_label, pvalue_text), + pos = 4, + col = "red" + ) + } + invisible(NULL) +} + +#' Draw the two-curve confidence-interval bounds panels +#' +#' Renders the paired normal curves centered at the lower and upper +#' confidence bounds, with the region beyond the observed statistic shaded. +#' +#' @param min_x Left plotting bound. +#' @param max_x Right plotting bound. +#' @param statistic Observed statistic. +#' @param lower Lower confidence bound. +#' @param upper Upper confidence bound. +#' @param curve_sd Standard deviation of the normal curves. +#' @param lower_title Title expression for the lower-bound panel. +#' @param upper_title Title expression for the upper-bound panel. +#' @param margin_label X-axis label drawn in the plot margin. +#' @param step_fn Function of two bounds returning the sequence step size. +#' +#' @return Invisibly `NULL`. +#' +#' @keywords internal +#' @noRd +.iscam_plot_ci_bounds_curves <- function( + min_x, + max_x, + statistic, + lower, + upper, + curve_sd, + lower_title, + upper_title, + margin_label, + step_fn +) { + CIseq <- seq(min_x, max_x, by = step_fn(min_x, max_x)) + plot(CIseq, dnorm(CIseq, lower, curve_sd), type = "l", xlab = " ") + mtext(margin_label, side = 1, line = 1.75, adj = 0.5, cex = 0.75) + topseq <- seq(statistic, max_x, by = step_fn(statistic, max_x)) + polygon( + c(statistic, topseq, max_x), + c(0, dnorm(topseq, lower, curve_sd), 0), + col = "red" + ) + title(lower_title) + upper_curve <- seq(min_x, max_x, by = step_fn(min_x, max_x)) + plot( + upper_curve, + dnorm(upper_curve, upper, curve_sd), + type = "l", + xlab = " " + ) + mtext(margin_label, side = 1, line = 1.75, adj = 0.5, cex = 0.75) + bottomseq <- seq(min_x, statistic, by = step_fn(min_x, statistic)) + polygon( + c(min_x, bottomseq, statistic, statistic), + c( + 0, + dnorm(bottomseq, upper, curve_sd), + dnorm(statistic, upper, curve_sd), + 0 + ), + col = "red" + ) + title(upper_title) + invisible(NULL) +} + +#' Draw the two-panel binomial confidence-interval bounds +#' +#' Renders the paired binomial mass functions centered at the lower and upper +#' confidence bounds, with spikes beyond the observed count highlighted. +#' +#' @param n Number of trials. +#' @param observed Observed successes. +#' @param minx Left x-limit (in counts). +#' @param maxx Right x-limit (in counts). +#' @param lower Lower confidence bound. +#' @param upper Upper confidence bound. +#' +#' @return Invisibly `NULL`. +#' +#' @keywords internal +#' @noRd +.iscam_plot_ci_binom_panels <- function(n, observed, minx, maxx, lower, upper) { + myxlab <- .iscam_binom_title(n, signif(lower, 4)) + plot( + seq(minx, maxx), + dbinom(seq(minx, maxx), size = n, prob = lower), + xlab = " ", + ylab = " ", + type = "h", + xlim = c(minx, maxx) + ) + mtext("Number of successes", side = 1, line = 1.75, adj = 0.5, cex = 0.75) + title(myxlab) + lines( + observed:n, + dbinom(observed:n, size = n, prob = lower), + col = "red", + type = "h" + ) + + myxlab <- .iscam_binom_title(n, signif(upper, 4)) + plot( + seq(minx, maxx), + dbinom(seq(minx, maxx), size = n, prob = upper), + xlab = " ", + ylab = " ", + type = "h", + xlim = c(minx, maxx) + ) + lines( + 0:observed, + dbinom(0:observed, size = n, prob = upper), + col = "red", + type = "h" + ) + mtext("Number of successes", side = 1, line = 1.75, adj = 0.5, cex = 0.75) + title(myxlab) + invisible(NULL) +} diff --git a/R/summary.R b/R/summary.R index d963332..ec9d527 100644 --- a/R/summary.R +++ b/R/summary.R @@ -29,11 +29,11 @@ iscamsummary <- function(x, explanatory = NULL, digits = 3) { } if (is.null(explanatory)) { - output <- .getSummaryStats(x) + output <- .iscam_summary_stats(x) } else { output <- as.data.frame(do.call( rbind, - tapply(x, explanatory, .getSummaryStats) + tapply(x, explanatory, .iscam_summary_stats) )) } round(output, digits) @@ -49,7 +49,7 @@ iscamsummary <- function(x, explanatory = NULL, digits = 3) { #' #' @keywords internal #' @noRd -.getSummaryStats <- function(x) { +.iscam_summary_stats <- function(x) { curried_quantile <- function(prob) { unname(quantile(x, probs = prob, na.rm = TRUE)) } diff --git a/R/t.R b/R/t.R index a7813aa..13f9d41 100644 --- a/R/t.R +++ b/R/t.R @@ -39,8 +39,7 @@ iscaminvt <- function(prob, df, direction, verbose = TRUE) { if (direction == "below") { answer <- signif(qt(prob, df, lower.tail = TRUE), 4) thisrange <- seq(min, answer, by = max(0.001, abs(answer - min) / 2000)) - # should we use min instead of zero? - polygon(c(thisrange, answer, 0), c(dt(thisrange, df), 0, 0), col = "pink") + polygon(c(thisrange, answer, min), c(dt(thisrange, df), 0, 0), col = "pink") text( (min + answer) / 2, dt(answer, df) / 2, @@ -113,7 +112,7 @@ iscaminvt <- function(prob, df, direction, verbose = TRUE) { text( answer1, min(dt(answer1, df), ymax * 0.85), - labels = bquote(T <= .(answer1)), + labels = bquote(T >= .(answer1)), col = "red", pos = 3 ) @@ -209,7 +208,6 @@ iscaminvt <- function(prob, df, direction, verbose = TRUE) { #' @param hypothesized Hypothesized population mean. #' @param alternative "less", "greater", or "two.sided" #' @param conf.level Confidence level. -#' @param verbose Logical; if `TRUE`, print textual descriptions of results. #' #' @return The t value, p value, and confidence interval. #' @@ -289,12 +287,12 @@ iscamonesamplet <- function( min <- min(-4, tvalue - 0.001) diffmin <- min( hypothesized - 4 * se, - hypothesized - abs(hypothesized - statistic) - 0.01 + hypothesized - abs(hypothesized - statistic) - 0.001 ) max <- max(4, tvalue + 0.001) diffmax <- max( hypothesized + 4 * se, - hypothesized + abs(hypothesized - statistic) + 0.01 + hypothesized + abs(hypothesized - statistic) + 0.001 ) x <- seq(min, max, by = max(0.001, abs(max - min) / 2000)) diffx <- x * se + hypothesized @@ -320,89 +318,48 @@ iscamonesamplet <- function( title(paste("t (df=", df, ")")) if (alternative == "less") { pvalue <- pt(tvalue, df) - drawseq <- seq( - diffmin, - statistic, - by = max(0.001, abs(statistic - diffmin) / 2000) - ) - polygon( - c(drawseq, statistic, diffmin), - c(dt((drawseq - hypothesized) / se, df), 0, 0), - col = "red" - ) - text( - diffmin, - dt(0, df) * 0.9, - labels = paste("t-statistic:", signif(tvalue, 3)), - pos = 4, - col = "blue" - ) - text( - diffmin, - dt(0, df) * 0.8, - labels = paste("p-value:", signif(pvalue, 4)), - pos = 4, - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = diffmin, + max_x = diffmax, + statistic = statistic, + density_fn = function(v) dt((v - hypothesized) / se, df), + step_fn = function(a, b) max(0.001, abs(b - a) / 2000), + statistic_label = "t-statistic:", + statistic_value = signif(tvalue, 3), + pvalue_label = "p-value:", + pvalue_text = signif(pvalue, 4) ) } else if (alternative == "greater") { pvalue <- 1 - pt(tvalue, df) - drawseq <- seq( - statistic, - diffmax, - by = max(0.001, abs(diffmax - statistic) / 2000) - ) - polygon( - c(statistic, drawseq, diffmax), - c(0, dt((drawseq - hypothesized) / se, df), 0), - col = "red" - ) - text( - diffmax, - dt(0, df) * 0.9, - labels = paste("t-statistic:", signif(tvalue, 3)), - pos = 2, - col = "blue" - ) - text( - diffmax, - dt(0, df) * 0.8, - labels = paste("p-value:", signif(pvalue, 4)), - pos = 2, - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = diffmin, + max_x = diffmax, + statistic = statistic, + density_fn = function(v) dt((v - hypothesized) / se, df), + step_fn = function(a, b) max(0.001, abs(b - a) / 2000), + statistic_label = "t-statistic:", + statistic_value = signif(tvalue, 3), + pvalue_label = "p-value:", + pvalue_text = signif(pvalue, 4) ) } else if (.iscam_is_two_sided_alt(alternative)) { pvalue <- 2 * pt(-1 * abs(tvalue), df) - drawseq <- .iscam_two_sided_draw_sequences( + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, min_x = diffmin, max_x = diffmax, - center = hypothesized, - statistic = statistic - ) - drawseq1 <- drawseq$left - drawseq2 <- drawseq$right - polygon( - c(diffmin, drawseq1, drawseq1[length(drawseq1)]), - c(0, dt((drawseq1 - hypothesized) / se, df), 0), - col = "red" - ) - polygon( - c(drawseq2[1], drawseq2, diffmax), - c(0, dt((drawseq2 - hypothesized) / se, df), 0), - col = "red" - ) - text( - diffmin, - dt(0, df) * 0.9, - labels = paste("t-statistic:", signif(tvalue, 4)), - pos = 4, - col = "blue" - ) - text( - diffmin, - dt(0, df) * 0.8, - labels = paste("two-sided p-value:", signif(pvalue, 4)), - pos = 4, - col = "red" + statistic = statistic, + density_fn = function(v) dt((v - hypothesized) / se, df), + step_fn = function(a, b) max(0.001, abs(b - a) / 2000), + statistic_label = "t-statistic:", + statistic_value = signif(tvalue, 4), + pvalue_label = "two-sided p-value:", + pvalue_text = signif(pvalue, 4) ) } } # end test @@ -436,55 +393,27 @@ iscamonesamplet <- function( if (is.null(alternative)) { min <- statistic - 4 * se max <- statistic + 4 * se - CIseq <- seq(min, max, by = max(0.001, abs(max - min) / 2000)) if (length(conf.level) == 1) { old <- par(mar = c(4, 0.5, 1.5, 0.5), mfrow = c(3, 1)) on.exit(par(old), add = TRUE) - myxlab <- substitute(paste(mean == x1), list(x1 = signif(lower[1], 4))) - plot(CIseq, dnorm(CIseq, lower[1], se), type = "l", xlab = " ") - mtext("sample means", side = 1, line = 1.75, adj = 0.5, cex = 0.75) - topseq <- seq( - statistic, - max, - by = max(0.001, abs(max - statistic) / 2000) - ) - polygon( - c(statistic, topseq, max), - c(0, dnorm(topseq, lower[1], se), 0), - col = "red" - ) - myxlab <- substitute( - paste("population mean", s == x1), - list(x1 = signif(lower[1], 4)) - ) - title(myxlab) - upper_curve <- seq(min, max, by = max(0.001, abs(max - min) / 2000)) - plot( - upper_curve, - dnorm(upper_curve, upper[1], se), - type = "l", - xlab = " " - ) - mtext("sample means", side = 1, line = 1.75, adj = 0.5, cex = 0.75) - bottomseq <- seq( - min, - statistic, - by = max(0.001, abs(statistic - min) / 2000) - ) - polygon( - c(min, bottomseq, statistic, statistic), - c( - 0, - dnorm(bottomseq, upper[1], se), - dnorm(statistic, upper[1], se), - 0 + .iscam_plot_ci_bounds_curves( + min_x = min, + max_x = max, + statistic = statistic, + lower = lower[1], + upper = upper[1], + curve_sd = se, + lower_title = substitute( + paste("population mean", s == x1), + list(x1 = signif(lower[1], 4)) + ), + upper_title = substitute( + paste("population mean", s == x1), + list(x1 = signif(upper[1], 4)) ), - col = "red" + margin_label = "sample means", + step_fn = function(a, b) max(0.001, abs(b - a) / 2000) ) - title(substitute( - paste("population mean", s == x1), - list(x1 = signif(upper[1], 4)) - )) } # just one interval for (k in seq_along(conf.level)) { .iscam_plot_ci_strip( @@ -505,8 +434,6 @@ iscamonesamplet <- function( cat("p-value:", pvalue, "\n") } } - old <- par(mfrow = c(1, 1)) - on.exit(par(old), add = TRUE) invisible() } @@ -526,7 +453,6 @@ iscamonesamplet <- function( #' @param hypothesized Hypothesized difference in population means. #' @param alternative "less", "greater", or "two.sided" #' @param conf.level Confidence level. -#' @param verbose Logical; if `TRUE`, print textual descriptions of results. #' #' @return The t value, p value, and confidence interval. #' @export @@ -578,7 +504,7 @@ iscamtwosamplet <- function( n2, hypothesized = 0, alternative = NULL, - conf.level = 0, + conf.level = NULL, verbose = TRUE ) { if (.iscam_maybe_help(x1, "iscamtwosamplet")) { @@ -646,10 +572,7 @@ iscamtwosamplet <- function( min <- min(-4, tvalue - 0.001) diffmin <- min( hypothesized - 4 * unpooledsd, - min( - hypothesized - 4 * unpooledsd, - hypothesized - abs(hypothesized - statistic) - 0.001 - ) + hypothesized - abs(hypothesized - statistic) - 0.001 ) max <- max(4, tvalue + 0.001) diffmax <- max( @@ -681,98 +604,57 @@ iscamtwosamplet <- function( if (alternative == "less") { pvalue <- signif(pt(tvalue, df), 4) tvalue <- signif(tvalue, 4) - drawseq <- seq( - diffmin, - statistic, - by = max(0.001, abs(statistic - diffmin) / 2000) - ) - polygon( - c(drawseq, statistic, diffmin), - c(dt((drawseq - hypothesized) / unpooledsd, df), 0, 0), - col = "red" - ) - text( - diffmin, - dt(0, df) * 0.9, - labels = paste("t-statistic:", tvalue), - pos = 4, - col = "blue" - ) - text( - diffmin, - dt(0, df) * 0.8, - labels = paste("p-value:", pvalue), - pos = 4, - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = diffmin, + max_x = diffmax, + statistic = statistic, + density_fn = function(v) dt((v - hypothesized) / unpooledsd, df), + step_fn = function(a, b) max(0.001, abs(b - a) / 2000), + statistic_label = "t-statistic:", + statistic_value = tvalue, + pvalue_label = "p-value:", + pvalue_text = pvalue ) } else if (alternative == "greater") { pvalue <- signif(1 - pt(tvalue, df), 4) tvalue <- signif(tvalue, 3) - drawseq <- seq( - statistic, - diffmax, - by = max(0.001, abs(diffmax - statistic) / 2000) - ) - polygon( - c(statistic, drawseq, diffmax), - c(0, dt((drawseq - hypothesized) / unpooledsd, df), 0), - col = "red" - ) - text( - diffmax, - dt(0, df) * 0.9, - labels = paste("t-statistic:", tvalue), - pos = 2, - col = "blue" - ) - text( - diffmax, - dt(0, df) * 0.8, - labels = paste("p-value:", pvalue), - pos = 2, - col = "red" + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, + min_x = diffmin, + max_x = diffmax, + statistic = statistic, + density_fn = function(v) dt((v - hypothesized) / unpooledsd, df), + step_fn = function(a, b) max(0.001, abs(b - a) / 2000), + statistic_label = "t-statistic:", + statistic_value = tvalue, + pvalue_label = "p-value:", + pvalue_text = pvalue ) } else if (.iscam_is_two_sided_alt(alternative)) { pvalue <- signif(2 * pt(-1 * abs(tvalue), df), 4) tvalue <- signif(tvalue, 4) - drawseq <- .iscam_two_sided_draw_sequences( + .iscam_draw_test_region( + alternative = alternative, + center = hypothesized, min_x = diffmin, max_x = diffmax, - center = hypothesized, - statistic = statistic - ) - drawseq1 <- drawseq$left - drawseq2 <- drawseq$right - polygon( - c(diffmin, drawseq1, drawseq1[length(drawseq1)]), - c(0, dt((drawseq1 - hypothesized) / unpooledsd, df), 0), - col = "red" - ) - polygon( - c(drawseq2[1], drawseq2, diffmax), - c(0, dt((drawseq2 - hypothesized) / unpooledsd, df), 0), - col = "red" - ) - text( - diffmin, - dt(0, df) * 0.9, - labels = paste("t-statistic:", tvalue), - pos = 4, - col = "blue" - ) - text( - diffmin, - dt(0, df) * 0.8, - labels = paste("two-sided p-value:", pvalue), - pos = 4, - col = "red" + statistic = statistic, + density_fn = function(v) dt((v - hypothesized) / unpooledsd, df), + step_fn = function(a, b) max(0.001, abs(b - a) / 2000), + statistic_label = "t-statistic:", + statistic_value = tvalue, + pvalue_label = "two-sided p-value:", + pvalue_text = pvalue ) } } lower <- NULL upper <- NULL - if (conf.level != 0) { + if (!is.null(conf.level)) { conf.level <- .iscam_normalize_conf_levels(conf.level) criticalvalue <- qt((1 - conf.level) / 2, df) lower <- statistic + criticalvalue * unpooledsd @@ -791,66 +673,28 @@ iscamtwosamplet <- function( if (is.null(alternative)) { min <- statistic - 4 * unpooledsd max <- statistic + 4 * unpooledsd - CIseq <- seq(min, max, by = max(0.001, abs(max - min) / 2000)) old <- par(mar = c(4, 0.5, 1.5, 0.5), mfrow = c(3, 1)) on.exit(par(old), add = TRUE) - myxlab <- substitute(paste(mean == x1), list(x1 = signif(lower, 4))) - plot(CIseq, dnorm(CIseq, lower, unpooledsd), type = "l", xlab = " ") - mtext( - "difference in sample means", - side = 1, - line = 1.75, - adj = 0.5, - cex = 0.75 - ) - topseq <- seq( - statistic, - max, - by = max(0.001, abs(max - statistic) / 2000) - ) - polygon( - c(statistic, topseq, max), - c(0, dnorm(topseq, lower, unpooledsd), 0), - col = "red" - ) - myxlab <- substitute( - paste("difference in population mean", s == x1), - list(x1 = signif(lower, 4)) - ) - title(myxlab) - upper_curve <- seq(min, max, by = max(0.001, abs(max - min) / 2000)) - plot( - upper_curve, - dnorm(upper_curve, upper, unpooledsd), - type = "l", - xlab = " " - ) - mtext( - "difference in sample means", - side = 1, - line = 1.75, - adj = 0.5, - cex = 0.75 - ) - bottomseq <- seq( - min, - statistic, - by = max(0.001, abs(statistic - min) / 2000) - ) - polygon( - c(min, bottomseq, statistic, statistic), - c( - 0, - dnorm(bottomseq, upper, unpooledsd), - dnorm(statistic, upper, unpooledsd), - 0 - ), - col = "red" - ) - title(substitute( - paste("difference in population mean", s == x1), - list(x1 = signif(upper, 4)) - )) + if (length(conf.level) == 1) { + .iscam_plot_ci_bounds_curves( + min_x = min, + max_x = max, + statistic = statistic, + lower = lower, + upper = upper, + curve_sd = unpooledsd, + lower_title = substitute( + paste("difference in population mean", s == x1), + list(x1 = signif(lower, 4)) + ), + upper_title = substitute( + paste("difference in population mean", s == x1), + list(x1 = signif(upper, 4)) + ), + margin_label = "difference in sample means", + step_fn = function(a, b) max(0.001, abs(b - a) / 2000) + ) + } .iscam_plot_ci_strip( min_x = min, @@ -876,8 +720,6 @@ iscamtwosamplet <- function( "upper" = upper )) } - old <- par(mfrow = c(1, 1)) - on.exit(par(old), add = TRUE) } #' Tail Probability for t-distribution @@ -888,7 +730,6 @@ iscamtwosamplet <- function( #' "outside" or "between" are used, a second larger observation, `xval2` must be #' specified #' @param xval2 second observation value. -#' @param verbose Logical; if `TRUE`, print textual descriptions of results. #' #' @return The tail probability in the specified direction using the given #' arguments. diff --git a/R/utils.R b/R/utils.R index d6fbb3f..07a0ace 100644 --- a/R/utils.R +++ b/R/utils.R @@ -34,6 +34,28 @@ } } +#' Convert proportion-like hypergeometric input to a count +#' +#' Treats values strictly between 0 and 1 as a proportion and rescales to an +#' expected count. +#' +#' @param k Hypergeometric count or proportion. +#' @param total Total number of observations in the study. +#' @param succ Overall number of successes. +#' @param n Number of observations in the first group. +#' +#' @return Observed count. +#' +#' @keywords internal +#' @noRd +.iscam_hyper_k_to_count <- function(k, total, succ, n) { + if (k < 1 && k > 0) { + round((k * n * (total - n) + n * succ) / total) + } else { + k + } +} + #' Resolve and validate two-value interval bounds #' #' @param xval First value. @@ -394,29 +416,19 @@ #' Map alternative string to symbolic comparator #' #' @param alternative Alternative hypothesis name. -#' @param include_not_equal Logical; if `TRUE`, map `"not.equal"` too. #' #' @return Single comparator symbol. #' #' @keywords internal #' @noRd -.iscam_alt_symbol <- function(alternative, include_not_equal = TRUE) { - if (include_not_equal) { - switch( - alternative, - less = "<", - greater = ">", - two.sided = "<>", - not.equal = "<>" - ) - } else { - switch( - alternative, - less = "<", - greater = ">", - two.sided = "<>" - ) - } +.iscam_alt_symbol <- function(alternative) { + switch( + alternative, + less = "<", + greater = ">", + two.sided = "<>", + not.equal = "<>" + ) } #' Print standardized null and alternative hypotheses @@ -426,7 +438,6 @@ #' @param alt_name Alternative-side parameter label. #' @param hypothesized Null value. #' @param alternative Alternative hypothesis name. -#' @param include_not_equal Logical passed to `.iscam_alt_symbol()`. #' #' @return Invisibly `NULL`. #' @@ -437,8 +448,7 @@ null_name, alt_name, hypothesized, - alternative, - include_not_equal = TRUE + alternative ) { if (!verbose) { return(invisible(NULL)) @@ -448,10 +458,7 @@ paste("Null hypothesis :", null_name, "=", hypothesized, sep = " "), "\n" ) - altname <- .iscam_alt_symbol( - alternative, - include_not_equal = include_not_equal - ) + altname <- .iscam_alt_symbol(alternative) cat( paste( "Alternative hypothesis:", @@ -466,6 +473,34 @@ invisible(NULL) } +#' Print the standard data summary line +#' +#' @param observed Observed count. +#' @param n Sample size. +#' @param verbose Logical controlling output. +#' +#' @return Invisibly `NULL`. +#' +#' @keywords internal +#' @noRd +.iscam_print_sample_summary <- function(observed, n, verbose) { + if (!verbose) { + return(invisible(NULL)) + } + statistic <- signif(observed / n, 4) + cat(paste( + "Data: observed successes = ", + observed, + ", sample size = ", + n, + ", sample proportion = ", + statistic, + "\n\n", + sep = "" + )) + invisible(NULL) +} + #' Add baseline and axis labels to an existing base plot #' #' @param x_label X-axis label. diff --git a/man/ISCAM-package.Rd b/man/ISCAM-package.Rd index 04b0b23..4301f90 100644 --- a/man/ISCAM-package.Rd +++ b/man/ISCAM-package.Rd @@ -22,6 +22,7 @@ Useful links: Authors: \itemize{ + \item Beth Chance \email{bchance@calpoly.edu} [copyright holder] \item Visruth Srimath Kandali \email{public@visruth.com} (\href{https://orcid.org/0009-0005-9097-0688}{ORCID}) } diff --git a/man/dot-add_density_common_params.Rd b/man/dot-iscam_add_density_common_params.Rd similarity index 85% rename from man/dot-add_density_common_params.Rd rename to man/dot-iscam_add_density_common_params.Rd index 66124e3..3b6ffc6 100644 --- a/man/dot-add_density_common_params.Rd +++ b/man/dot-iscam_add_density_common_params.Rd @@ -1,7 +1,7 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/overlayDensities.R -\name{.add_density_common_params} -\alias{.add_density_common_params} +\name{.iscam_add_density_common_params} +\alias{.iscam_add_density_common_params} \title{Template documentation for plotting arguments} \arguments{ \item{x}{A numeric vector representing the data to be plotted.} diff --git a/man/dot-plot_funcs_common_params.Rd b/man/dot-iscam_plot_funcs_common_params.Rd similarity index 87% rename from man/dot-plot_funcs_common_params.Rd rename to man/dot-iscam_plot_funcs_common_params.Rd index f9ee015..830c9d7 100644 --- a/man/dot-plot_funcs_common_params.Rd +++ b/man/dot-iscam_plot_funcs_common_params.Rd @@ -1,7 +1,7 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{.plot_funcs_common_params} -\alias{.plot_funcs_common_params} +\name{.iscam_plot_funcs_common_params} +\alias{.iscam_plot_funcs_common_params} \title{Template documentation for plotting arguments} \arguments{ \item{response}{Vector of numeric values to plot.} diff --git a/man/iscamtwosamplet.Rd b/man/iscamtwosamplet.Rd index 4d65f46..cbfc55c 100644 --- a/man/iscamtwosamplet.Rd +++ b/man/iscamtwosamplet.Rd @@ -13,7 +13,7 @@ iscamtwosamplet( n2, hypothesized = 0, alternative = NULL, - conf.level = 0, + conf.level = NULL, verbose = TRUE ) } diff --git a/tests/testthat/_snaps/binomial.md b/tests/testthat/_snaps/binomial.md index 940e5f0..d537261 100644 --- a/tests/testthat/_snaps/binomial.md +++ b/tests/testthat/_snaps/binomial.md @@ -153,7 +153,7 @@ [4] "Data: observed successes = 13, sample size = 24, sample proportion = 0.5417" [5] "" [6] "Null hypothesis : pi = 0.5 " - [7] "Alternative hypothesis: pi 0.5 " + [7] "Alternative hypothesis: pi <> 0.5 " [8] "p-value: 0.83882 " # iscambinomtest returns single confidence intervals without hypothesis diff --git a/tests/testthat/_snaps/darwin/t/iscaminvt-below.svg b/tests/testthat/_snaps/darwin/t/iscaminvt-below.svg index 5dd28f7..f6f216c 100644 --- a/tests/testthat/_snaps/darwin/t/iscaminvt-below.svg +++ b/tests/testthat/_snaps/darwin/t/iscaminvt-below.svg @@ -71,7 +71,7 @@ t (df = 15 ) - + 0.05 T ≤ diff --git a/tests/testthat/_snaps/linux/t/iscaminvt-below.svg b/tests/testthat/_snaps/linux/t/iscaminvt-below.svg index 80b4d9e..345e61f 100644 --- a/tests/testthat/_snaps/linux/t/iscaminvt-below.svg +++ b/tests/testthat/_snaps/linux/t/iscaminvt-below.svg @@ -71,7 +71,7 @@ t (df = 15 ) - + 0.05 T ≤ diff --git a/tests/testthat/_snaps/windows/t/iscaminvt-below.svg b/tests/testthat/_snaps/windows/t/iscaminvt-below.svg index 80b4d9e..345e61f 100644 --- a/tests/testthat/_snaps/windows/t/iscaminvt-below.svg +++ b/tests/testthat/_snaps/windows/t/iscaminvt-below.svg @@ -71,7 +71,7 @@ t (df = 15 ) - + 0.05 T ≤ diff --git a/tests/testthat/test-t.R b/tests/testthat/test-t.R index affb2e5..4700694 100644 --- a/tests/testthat/test-t.R +++ b/tests/testthat/test-t.R @@ -326,7 +326,11 @@ test_that("iscamtwosamplet returns Welch two-sample results", { lower <- (x1 - x2) + critical * se upper <- (x1 - x2) - critical * se - expect_null(res$value) + expect_equal(res$value$tvalue, t_expected, tolerance = 1e-3) + expect_equal(res$value$df, df_expected, tolerance = 1e-3) + expect_equal(res$value$pvalue, p_expected, tolerance = 1e-4) + expect_equal(res$value$lower, lower, tolerance = 1e-3) + expect_equal(res$value$upper, upper, tolerance = 1e-3) expect_snapshot(res$output) }) @@ -349,7 +353,9 @@ test_that("iscamtwosamplet handles less alternative", { t_expected <- (4.5 - 5.1) / se p_expected <- pt(t_expected, df = df_calc) - expect_null(res$value) + expect_equal(res$value$tvalue, t_expected, tolerance = 1e-3) + expect_equal(res$value$df, df_calc, tolerance = 1e-3) + expect_equal(res$value$pvalue, p_expected, tolerance = 1e-4) output <- collapse_output(res$output) get_value <- function(label) { match <- regexpr(paste0(label, ": [-0-9.]+"), output) @@ -376,7 +382,14 @@ test_that("iscamtwosamplet handles greater alternative", { verbose = FALSE ))) - expect_null(res$value) + expect_equal( + res$value$pvalue, + 1 - pt((5.8 - 5.1) / sqrt(1.1^2 / 22 + 1.3^2 / 20), + df = (1.1^2 / 22 + 1.3^2 / 20)^2 / + ((1.1^2 / 22)^2 / 21 + (1.3^2 / 20)^2 / 19) + ), + tolerance = 1e-4 + ) }) test_that("iscamtwosamplet provides intervals without hypothesis test", { diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index a01101b..ffdbcec 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -56,6 +56,135 @@ test_that("discrete tail region helper works for both tails", { expect_equal(upper$corrected_cutoff, 2.5) }) +test_that("discrete tail region helper handles out-of-range cutoffs", { + # jarl-ignore internal_function: testing internal function + below <- ISCAM:::.iscam_discrete_tail_regions( + k = -1, + lower_bound = 0, + upper_bound = 10, + lower.tail = TRUE, + correction = 0.5, + step = 1 + ) + # jarl-ignore internal_function: testing internal function + above <- ISCAM:::.iscam_discrete_tail_regions( + k = 11, + lower_bound = 0, + upper_bound = 10, + lower.tail = FALSE, + correction = 0.5, + step = 1 + ) + + expect_equal(below$corrected_cutoff, -0.5) + expect_equal(below$corrected_seq, 0) + expect_equal(above$corrected_cutoff, 10.5) + expect_equal(above$corrected_seq, 10.5) +}) + +test_that("discrete tail probability printer handles both tails", { + # jarl-ignore internal_function: testing internal function + expect_output( + ISCAM:::.iscam_print_discrete_tail_probability(TRUE, 3, 0.5, TRUE), + "Probability 3 and below = 0.5" + ) + # jarl-ignore internal_function: testing internal function + expect_output( + ISCAM:::.iscam_print_discrete_tail_probability(TRUE, 3, 0.5, FALSE), + "Probability 3 and above = 0.5" + ) + # jarl-ignore internal_function: testing internal function + expect_null( + ISCAM:::.iscam_print_discrete_tail_probability(FALSE, 3, 0.5, TRUE) + ) +}) + +test_that("alternative symbols map one- and two-sided names", { + # jarl-ignore internal_function: testing internal function + expect_equal(ISCAM:::.iscam_alt_symbol("less"), "<") + # jarl-ignore internal_function: testing internal function + expect_equal(ISCAM:::.iscam_alt_symbol("greater"), ">") + # jarl-ignore internal_function: testing internal function + expect_equal(ISCAM:::.iscam_alt_symbol("two.sided"), "<>") + # jarl-ignore internal_function: testing internal function + expect_equal(ISCAM:::.iscam_alt_symbol("not.equal"), "<>") +}) + +test_that("binomial plot limits wrap to the support range", { + # jarl-ignore internal_function: testing internal function + limits <- ISCAM:::.iscam_binom_limits(10, 0.1) + expect_equal(limits, c(0, 4.794733), tolerance = 1e-5) + # jarl-ignore internal_function: testing internal function + expect_equal( + ISCAM:::.iscam_binom_limits(10, 0.1, include_upper = 5), + c(0, 5) + ) + # jarl-ignore internal_function: testing internal function + expect_equal( + ISCAM:::.iscam_binom_limits(10, 0.1, include_upper = 4), + c(0, 4.794733), + tolerance = 1e-5 + ) +}) + +test_that("exact binomial confidence intervals match binom.test", { + # jarl-ignore internal_function: testing internal function + mid <- ISCAM:::.iscam_binom_ci(5, 10, 0.95) + expect_equal( + as.numeric(mid), + as.numeric(binom.test(5, 10, conf.level = 0.95)$conf.int), + tolerance = 1e-12 + ) + # jarl-ignore internal_function: testing internal function + expect_equal( + ISCAM:::.iscam_binom_ci(0, 10, 0.95), + c(lower = 0, upper = 1 - 0.025^(1 / 10)), + tolerance = 1e-12 + ) + # jarl-ignore internal_function: testing internal function + expect_equal( + ISCAM:::.iscam_binom_ci(10, 10, 0.95), + c(lower = 0.025^(1 / 10), upper = 1), + tolerance = 1e-12 + ) +}) + +test_that("internal binomial plotting helpers run and return p-values", { + # jarl-ignore internal_function: testing internal function + capture_plot_result(ISCAM:::.iscam_plot_binom_distribution(10, 0.5, c(0, 10))) + # jarl-ignore internal_function: testing internal function + capture_plot_result( + ISCAM:::.iscam_plot_binom_distribution(10, 0.5, c(0, 10), add_title = FALSE) + ) + # jarl-ignore internal_function: testing internal function + res_less <- capture_plot_result({ + ISCAM:::.iscam_plot_binom_distribution(15, 0.4, c(0, 15), add_title = FALSE) + ISCAM:::.iscam_plot_exact_binom_region(6, 15, 0.4, "less", 0, 15, 0.5) + }) + # jarl-ignore internal_function: testing internal function + res_greater <- capture_plot_result({ + ISCAM:::.iscam_plot_binom_distribution(18, 0.45, c(0, 18), add_title = FALSE) + ISCAM:::.iscam_plot_exact_binom_region(11, 18, 0.45, "greater", 0, 18, 0.5) + }) + # jarl-ignore internal_function: testing internal function + res_two <- capture_plot_result({ + ISCAM:::.iscam_plot_binom_distribution(24, 0.5, c(0, 24), add_title = FALSE) + ISCAM:::.iscam_plot_exact_binom_region(13, 24, 0.5, "two.sided", 0, 24, 0.5) + }) + + expect_equal(res_less$value, pbinom(6, 15, 0.4)) + expect_equal( + res_greater$value, + pbinom(10, 18, 0.45, lower.tail = FALSE) + ) + two_sided_cutoff <- dbinom(13, 24, 0.5) + 1e-5 + two_sided_mass <- dbinom(0:24, 24, 0.5) + expect_equal( + res_two$value, + sum(two_sided_mass[two_sided_mass <= two_sided_cutoff]) + ) +}) + test_that("normal approximation helper returns exact and corrected tails", { # jarl-ignore internal_function: testing internal function lower <- ISCAM:::.iscam_normal_tail_probs_with_cc(