Skip to content

Instantly share code, notes, and snippets.

@carbocation
Last active December 16, 2023 21:50
Show Gist options
  • Save carbocation/d39a20ed028b25ff3528468b455b2bcc to your computer and use it in GitHub Desktop.
Save carbocation/d39a20ed028b25ff3528468b455b2bcc to your computer and use it in GitHub Desktop.
Compute extreme P values from Z scores or T scores and degrees of freedom. Note: these are two-tailed (log(2) + ...) where two-tailed tests are appropriate. The Z and T functions can be run online at https://tools.carbocation.com/ExtremeP
# Via https://stackoverflow.com/a/46416222/199475
pvalue.extreme.z <- function(z) {
log.pvalue <- log(2) + pnorm(abs(z), lower.tail = FALSE, log.p = TRUE)
log10.pvalue <- log.pvalue/log(10) ## from natural log to log10
mantissa <- 10^(log10.pvalue %% 1)
exponent <- log10.pvalue %/% 1
return(list(mantissa=mantissa,exponent=exponent))
}
# Modified to the t-score approach from the Z-score based approach on https://stackoverflow.com/a/46416222/199475
pvalue.extreme.t <- function(t, df) {
log.pvalue <- log(2) + pt(abs(t), df=df, lower.tail = FALSE, log.p = TRUE)
log10.pvalue <- log.pvalue/log(10) ## from natural log to log10
mantissa <- 10^(log10.pvalue %% 1)
exponent <- log10.pvalue %/% 1
return(list(mantissa=mantissa,exponent=exponent))
}
# Modified from the Z-score based approach on https://stackoverflow.com/a/46416222/199475
pvalue.extreme.f <- function(f, df1, df2) {
log.pvalue <- pf(abs(f), df1, df2, lower.tail = FALSE, log.p = TRUE)
log10.pvalue <- log.pvalue/log(10) ## from natural log to log10
mantissa <- 10^(log10.pvalue %% 1)
exponent <- log10.pvalue %/% 1
return(list(mantissa=mantissa,exponent=exponent))
}
# Modified to the chi-square score approach from the Z-score based approach on https://stackoverflow.com/a/46416222/199475
pvalue.extreme.chisq <- function(chisq, df) {
log.pvalue <- log(2) + pchisq(chisq, df = df, lower.tail = FALSE, log.p = TRUE)
log10.pvalue <- log.pvalue / log(10)
mantissa <- 10^(log10.pvalue %% 1)
exponent <- log10.pvalue %/% 1
return(list(mantissa=mantissa,exponent=exponent))
}
# Modified to the chisq approach based on SAIGE: https://rdrr.io/github/weizhouUMICH/SAIGE/src/R/SAIGE_SPATest.R
pvalue.extreme.saiget <- function(t, varT, df) {
return(pvalue.extreme.chisq(t^2/varT, df))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment