Nothing
# PA-FGRS related helper functions ----------------------------------------
#' Title: Calculate the mean of the truncated normal distribution
#'
#' @param mu mean value of normal distribution
#' @param sigma standard deviation of normal distribution
#' @param lower lower threshold
#' @param upper upper threshold
#'
#' @returns mean value of the truncated normal distribution
#' @export
#'
#' @importFrom stats dnorm pnorm
#' @examples
#' tnorm_mean()
tnorm_mean = function(mu = 0, sigma = 1, lower = -Inf, upper = Inf) {
# calculate the mean of the truncated normal distribution
# using the formula from https://en.wikipedia.org/wiki/Truncated_normal_distribution
if (upper == -Inf | lower == Inf) stop("tnorm_mean: you may have switched the lower and upper bounds!")
# returns normal distribution mean of thresholds are -Inf and Inf
if (lower == -Inf & upper == Inf) {
return(mu)
}
# if lower and upper bounds are the same, we will interpret it as a normal distribution with 0 variance
# and mean equal to the limits, which can be interpreted as a direc delta function on the limit's values
if (lower == upper) {
return(lower)
}
# Otherwise, we will use the general formula
alpha = (lower - mu) / sigma
beta = (upper - mu) / sigma
return(mu - sigma * (dnorm(beta) - dnorm(alpha)) / (pnorm(beta) - pnorm(alpha)))
}
#' Title: Calculate the variance of the truncated normal distribution
#'
#' @param mu mean value of normal distribution
#' @param sigma standard deviation of normal distribution
#' @param lower lower threshold
#' @param upper upper threshold
#'
#' @returns mean value of the truncated normal distribution
#' @export
#'
#' @importFrom stats dnorm pnorm
#' @examples
#' tnorm_var()
tnorm_var = function(mu = 0, sigma = 1, lower = -Inf, upper = Inf) {
# calculate the variance of the truncated normal distribution
# using the formula from https://en.wikipedia.org/wiki/Truncated_normal_distribution
if (upper == -Inf | lower == Inf) stop("tnorm_mean: you may have switched the lower and upper bounds!")
# if the bounds are infinite, the variance of the normal distribution is returned
if (lower == -Inf & upper == Inf) {
return(sigma^2)
}
# if lower and upper bounds are the same, we will interpret it as a normal
# distribution with 0 variance (direc distribution on the mean)
if (lower == upper) {
return(0)
}
# Otherwise, we will use the general formula(s)
alpha = (lower - mu) / sigma
beta = (upper - mu) / sigma
# we will use the special cases to handle infinite bounds, since they may results in NaNs by, e.g. Inf * 0
if ( beta == Inf ) {
return(sigma^2 * (1 + (alpha * dnorm(alpha)) / (1 - pnorm(alpha)) - (dnorm(alpha))^2 / (1 - pnorm(alpha))^2))
}
if ( alpha == -Inf ) {
return(sigma^2 * (1 - (beta * dnorm(beta)) / pnorm(beta) - (dnorm(beta))^2 / pnorm(beta)^2))
}
# if both alpha and beta are finite we do not experience any NaNs with the general formula
return(sigma^2 * (1 + (alpha * dnorm(alpha) - beta * dnorm(beta)) / (pnorm(beta) - pnorm(alpha)) - (dnorm(alpha) - dnorm(beta))^2 / (pnorm(beta) - pnorm(alpha))^2))
}
#' Title: Calculates mean and variance of mixture of two truncated normal distributions
#'
#' @param mu Mean value of normal distribution.
#' @param var Variance of normal distribution.
#' @param lower Lower threshold (can be -Inf).
#' @param upper Upper threshold (can be Inf).
#' @param K_i (Stratified) cumulative incidence proportion for the individual.
#' @param K_pop Population prevalence (cumulative incidence proportion).
#'
#' @returns mean and variance of mixture distribution between two truncated normal distributions
#' @export
#'
#' @importFrom dplyr case_when
#' @examples
#' tnorm_mixture_conditional(mu = 0, var = 1, lower = -Inf, upper = Inf, K_i = 0, K_pop = 0.01)
#' tnorm_mixture_conditional(mu = 0, var = 1, lower = -Inf, upper = 2, K_i = .01, K_pop = 0.05)
tnorm_mixture_conditional = function(mu, var, lower, upper, K_i, K_pop) {
# converting to sd for computations
cur_sigma = sqrt(var)
# K_i and K_pop must be supplied together or not at all: both NA is the
# legitimate "no mixture requested" case (mixture_prob is forced to 1
# below), but exactly one being NA is ambiguous input, most likely a data
# problem upstream (e.g. K_i's per-row CIP merge failed to find a match
# while K_pop's per-stratum lookup still succeeded). Previously this was
# silently allowed to enter the mixture branch and propagate as an all-NA
# result (e.g. K_pop - NA = NA) instead of failing clearly.
if (xor(is.na(K_i), is.na(K_pop))) {
stop("tnorm_mixture_conditional: K_i and K_pop must either both be provided or both be NA (got K_i = ",
K_i, ", K_pop = ", K_pop, ").")
}
# are calculations required for mixture probabilities?
# This must stay the exact logical negation of the "no future tail needed"
# condition used for m1/sd1 below (upper == Inf | lower == upper) - the
# mixture only makes sense when there IS a real tail beyond `upper` left
# to weigh against. Previously this used `upper != Inf | lower == upper`
# (an OR, not the negation), which meant lower == upper - i.e. a known
# case, dirac point mass on `upper`, as produced by
# prepare_thresholds(..., lower_equal_upper = TRUE) - still fired the
# mixture calculation even though m1/sd1 are forced to 0 for that same
# condition. That silently shrunk known cases' mean toward 0 by a spurious
# mixture_prob factor and inflated their variance away from the correct
# exact 0, whenever K_i/K_pop were supplied (i.e. under PA-FGRS).
if ( !is.na(K_i) & (upper != Inf & lower != upper) ) {
# enter here if K_i and K_pop are provided and individual is NOT a case
# T and cdf values needed for mixture prob:
thr_pop = qnorm(K_pop, lower.tail = FALSE)
cdf_pop = pnorm((thr_pop - mu) / cur_sigma)
# mixture prob - eq s3 supp notes of PA-FGRS (slightly modified)
# the supp notes indicate that 1 - mixture prob should have been given as below
# However, that seemed to lead to incorrect estimates, hence the change.
mixture_prob = cdf_pop / (cdf_pop + (1 - cdf_pop) * (K_pop - K_i) / K_pop)
} else {
# mean and var is updated only through m0 and sd0
mixture_prob = rep(1, length(K_i))
}
# # calculating mixture probabilities
# w_below = case_when(
# K_i == 0 ~ pnorm(upper, mean = mu, sd = cur_sigma),
# upper == Inf | upper == lower | is.na(K_i) ~ 1,
# TRUE ~ pnorm(upper, mean = mu, sd = cur_sigma) / (1 - pnorm(upper, mean = mu, sd = cur_sigma, lower.tail = FALSE) * K_i / pnorm(upper, lower.tail = FALSE))
# )
# w_above = 1 - w_below
# new mean - eq s4 supp notes of PA-FGRS
m0 = tnorm_mean(mu = mu, sigma = cur_sigma, lower = lower, upper = upper)
m1 = ifelse(upper == Inf | lower == upper,
0, # if case
tnorm_mean(mu = mu, sigma = cur_sigma, lower = upper, upper = Inf)) # if control
new_mean = mixture_prob * m0 + (1 - mixture_prob) * m1
# new variance - eq S5 supp notes of PA-FGRS
sd0 = tnorm_var(mu = mu, sigma = cur_sigma, lower = lower, upper = upper)
sd1 = ifelse(upper == Inf | lower == upper,
0, # if case
tnorm_var(mu = mu, sigma = cur_sigma, lower = upper, upper = Inf)) # if control
new_var = mixture_prob * (m0^2 + sd0) + (1 - mixture_prob) * (m1^2 + sd1) - new_mean^2
return(list(mean = new_mean, var = new_var))
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.