Created
January 23, 2018 10:57
-
-
Save wpetry/044906b6df680daf131cfebd27cd32b3 to your computer and use it in GitHub Desktop.
Format p-values for Rmarkdown publications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################# | |
## Format p-values for use in Rmarkdown documents | |
## This function modifies base::format.pval() to automate | |
## the inclusion of equalities and inequalities | |
## Author: W.K. Petry | |
################################################# | |
# Arguments: | |
# pv a numeric vector | |
# digits how many significant digits to use; recommended value is 3 | |
# eps numerical tolerance; effectively the smallest p-value to report; recommended value is 10^(-digits) | |
# na.form character representation of NAs in the output | |
# appendequal logical; whether or not to add a leading "=" when 10^(-digits) < pv < 1-10^(-digits) | |
# sep character separator between the (in)equality symbol and the formatted p-value | |
# Value: | |
# A character vector. | |
# Examples: | |
# my_pvals <- c(stats::runif(5), pi^-100, NA) | |
# base::format.pval(my_pvals) | |
# format_pval(my_pvals) | |
# | |
# more_pvals <- c(0.1, 0.0001, 1e-27) | |
# format_pval(more_pvals) | |
# format_pval(more_pvals, digits = 3, eps = 10^-3) | |
# format_pval(more_pvals, digits = 3, eps = 10^-6) | |
# | |
# format_pval(more_pvals, appendequal = FALSE, sep = "") | |
################################################# | |
format_pval <- function (pv, digits = max(1L, getOption("digits") - 2L), | |
eps = .Machine$double.eps, na.form = "NA", | |
appendequal = TRUE, sep = " ", ...) { | |
if ((has.na <- any(ina <- is.na(pv)))) | |
pv <- pv[!ina] | |
r <- character(length(is0 <- pv < eps)) | |
is1 <- (1 - pv) < 10^-digits | |
if (any(!is0 & !is1)) { | |
rr <- pv <- pv[!is0 & !is1] | |
expo <- floor(log10(ifelse(pv > 0, pv, 1e-50))) | |
fixp <- expo >= -3 | (expo == -4 & digits > 1) | |
if (any(fixp)) | |
rr[fixp] <- format(pv[fixp], digits = digits, ...) | |
if (any(!fixp)) | |
rr[!fixp] <- format(pv[!fixp], digits = digits, ...) | |
r[!is0 & !is1] <- if (appendequal == TRUE) | |
paste("=", rr) | |
else rr | |
} | |
if (any(is0)) { | |
r[is0] <- paste("<", format(eps, digits = digits, ...), | |
sep = sep) | |
} | |
if (any(is1)) { | |
r[is1] <- paste(">", format(1-10^-digits, digits = digits, ...), | |
sep = sep) | |
} | |
if (has.na) { | |
rok <- r | |
r <- character(length(ina)) | |
r[!ina] <- rok | |
r[ina] <- na.form | |
} | |
r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment