Confidence Intervals

A small little function written in R to get the 95% confidence intervals and some quick stats of a vector. I found this useful in error reporting in some stats. I got the concept from this tutorial.

This does require the dplyr library

Function

library( dplyr )

ci <- function( x ){
  cnf <- dplyr::tibble(
    mean = mean( x, na.rm = TRUE),
    st.dev = sd( x, na.rm = TRUE),
    n = length( x ),
    error = qnorm( 0.975 ) * st.dev / sqrt( n ),
    ci05 = mean - error,
    ci95 = mean + error
  )
  
  cat( cnf$mean, "(", cnf$ci05, "-", cnf$ci95, ")\n" )
  return( cnf )
}

Use

> x <- sample(10)
> ci(x)
5.5 ( 3.623477 - 7.376523 )
# A tibble: 1 x 6
   mean st.dev     n error  ci05  ci95
  <dbl>  <dbl> <int> <dbl> <dbl> <dbl>
1   5.5   3.03    10  1.88  3.62  7.38