Friday, March 26, 2021

Calculate sample mean and its confidence interval using t-distribution

sample.mean.CI <- function(x, log.transform = FALSE)
{
    ## Purpose: Calculate sample mean and its confidence interval using t-distribution
    ## Arguments:
    ##   x: a vector of numeric values
    ##   log.transform: if T, apply log transformation to the data first. 
    ## Return: print sample mean and its confidence interval
    ## Author: Feiming Chen
    ## ________________________________________________

    if (log.transform) {
        x <- log(x)
    }
    r <- t.test(x)
    e <- r$estimate
    c1 <- r$conf.int[1]
    c2 <- r$conf.int[2]

    if (log.transform) {
        e <- exp(e)
        c1 <- exp(c1)
        c2 <- exp(c2)
    }
    
    ans <- c(e, c1, c2)
    cat("Mean = ", convert.to.CI.text(ans), "\n")
    ans

}
if (F) {                                # Unit Test
    set.seed(1)
    sample.mean.CI(rnorm(100))          # Mean =  0.11 (-0.07 , 0.29) 
    sample.mean.CI(c(1, 2, 5, 10, 100), log.transform = TRUE) # Mean =  6.31 (0.7 , 57.23) 
}


No comments:

Post a Comment