I want to calculate a confidence interval for a vector of normally distributed values in R. Doing this manually would not be too big of a hassle but surely there is an inbuilt function for this. I can't seem to find one though. Any ideas?
2 Answers
I'm not sure if there is a function for this, but a simple way to do this is to fit a model with intercept only and extract the confidence interval from that with the confint
function.
set.seed(1)
x <- rnorm(20)
m <- lm(x~1)
confint(m)
2.5 % 97.5 %
(Intercept) -0.236892 0.6179398
There is no a built-in function for precisely this and only this purpose. I guess the reason is that it really is very easy to compute manually. Let, as in the @bobbel's answer,
set.seed(1)
x <- rnorm(20)
Then one way to extract the interval would be
t.test(x)$conf.int
# [1] -0.2368920 0.6179398
# attr(,"conf.level")
# [1] 0.95
which is not a bad idea as often you will want to do the test anyway. As to get the interval alone, you are going to need to define your own function, e.g.,
normConfInt <- function(x, alpha = 0.05)
mean(x) + qt(1 - alpha / 2, length(x) - 1) * sd(x) / sqrt(length(x)) * c(-1, 1)
normConfInt(x)
# [1] -0.2368920 0.6179398