Skip to content

Instantly share code, notes, and snippets.

@TonyLadson
Created February 5, 2016 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TonyLadson/cc75e342b55e42ce51bb to your computer and use it in GitHub Desktop.
Save TonyLadson/cc75e342b55e42ce51bb to your computer and use it in GitHub Desktop.
# Confidence intervals for the mean for non-normal data
# See https://tonyladson.wordpress.com/2016/01/11/plotting-water-quality-samples-on-a-hydrograph/
# Modified Cox function for calculating confidence intervals for the mean
# Based on Olsson, 2005
# http://www.amstat.org/publications/jse/v13n1/olsson.html
# x is a set of log-normal data
ModifiedCox <- function(x){
n <- length(x)
y <- log(x)
y.m <- mean(y)
y.var <- var(y)
my.t <- qt(0.975, df = n-1)
my.mean <- y.m + y.var/2
upper <- y.m + y.var/2 + my.t*sqrt(y.var/n + y.var^2/(2*(n - 1)))
lower <- y.m + y.var/2 - my.t*sqrt(y.var/n + y.var^2/(2*(n - 1)))
return(list(upper = exp(upper), mean = exp(my.mean), lower = exp(lower)))
}
Singleton <- c(76.26, 171.87, 218.21, 668.79, 1374.42, 124.12,
276.30, 895.50, 1374.42, 280.18, 202.62, 4052.42,
2323.77, 2536.31, 3315.62, 1232.73,1391.43,
12525.66, 1099.54, 447.75, 478.92, 180.52, 164.36,
229.54, 2125.4, 966.35, 2751.68, 49.03, 79.51, 912.5, 926.67)
ModifiedCox(Singleton)
$upper
[1] 2973.871
$mean
[1] 1401.69
$lower
[1] 763.9697
# Bootstrapping
# See http://stats.stackexchange.com/questions/112829/how-do-i-calculate-confidence-intervals-for-a-non-normal-distribution/193940#193940
# function to obtain the mean
Bmean <- function(data, i) {
d <- data[i] # allows boot to select sample
return(mean(d))
}
# bootstrapping with 1000 replications
results <- boot(data=Singleton, statistic=Bmean, R=1000)
# view results
results
plot(results)
# get 95% confidence interval
boot.ci(results, type=c("norm", "basic", "perc", "bca"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment