R/confidence_intervals.R

Defines functions ci_sd ci_mean

Documented in ci_mean ci_sd

#' Estimate sample mean with student/normal confidence intervals
#'
#' @param x data set
#' @param sig_lvl significance level
#'
#' @description {The well known confidence interval for population mean.}
#' @details {For small samples, student-t distribution is used, for large samples, normal distribution is used.}
#' @return data.frame containing the lower bounded, the estimate, and the upper bound.
#' @export ci_mean
ci_mean <- function(x, sig_lvl = 0.05)
{
  mu <- mean(x)
  volat <- stats::sd(x)
  n <- length(x)
  if(n <= 45)
  {
    # Use Student-t
    # Use normal
    t_alpha <- stats::qt(1-sig_lvl/2, df = n-1)
    err <- t_alpha*volat/sqrt(n)
    lb <- mu-err
    ub <- mu+err
  } else if(n > 45)
  {
    # Use normal
    z_alpha <- stats::qnorm(1-sig_lvl/2)
    volat <- stats::sd(x)

    err <- z_alpha*volat/sqrt(n)
    lb <- mu-err
    ub <- mu+err

  }
  return(data.frame(lb = lb, mu = mu, ub = ub, err = err, n = n, cl = 1-sig_lvl))
}

#' Estimate sample standard deviation with chi-square confidence interval
#'
#' @param x data set
#' @param sig_lvl significance level
#'
#' @description {The well known confidence interval for population standard deviation.}
#' @details {Uses the Chi-square distribution of the sample variance and takes root of interval for variance.}
#' @return data.frame containing the lower bounded, the estimate, and the upper bound.
#' @export ci_sd
ci_sd <- function(x, sig_lvl = 0.05)
{
  volat2 <- stats::var(x)
  n <- length(x)
  chiAlpha1 <- stats::qchisq(1-sig_lvl/2, df = n-1)
  chiAlpha2 <- stats::qchisq(sig_lvl/2, df = n-1)
  lb <- (n-1)*volat2/chiAlpha1
  ub <- (n-1)*volat2/chiAlpha2
  return(data.frame(lb = sqrt(lb), volat = sqrt(volat2), ub = sqrt(ub), n = n, cl = 1-sig_lvl))
}
shill1729/pside documentation built on June 11, 2020, 12:18 a.m.