I tried figuring out the formula that the RMISC package uses but I wasn't sure, I couldn't find the documentation on it? I tried using the t, and Z statistic but it wasn't giving me the same answer as this package. Any recommendations?
1 Answer
The CI
function uses the following formula:
$$ \bar{x} \pm t_{\alpha/2, n-1}\times \frac{s}{\sqrt{n}} $$ where $t_{\alpha/2, n-1}$ is the upper $\alpha/2$ critical point of a $t$ distribution with $n-1$ degrees of freedom.
Example
In the following example, I'm drawing 50 random variables from a normal distribution with mean 100 and standard deviation 15 (the values don't matter).
library(Rmisc)
set.seed(142857)
x <- rnorm(50, 100, 15) # draw 50 rvs from a normal distribution
xbar <- mean(x)
s <- sd(x)
n <- length(x)
# Calculate the confidence interval by hand
xbar + c(-1, 1)*qt(0.975, n -1)*(s/sqrt(n))
[1] 96.18685 105.28056
# Use the "CI" function from the package
CI(x, 0.95)
upper mean lower
105.28056 100.73370 96.18685
The two confidence limits are exactly the same.
To see what formula the function CI
uses, you can look at the source code by typing CI
in to the R console without the parentheses. Like that:
CI
function (x, ci = 0.95)
{
a <- mean(x)
s <- sd(x)
n <- length(x)
error <- qt(ci + (1 - ci)/2, df = n - 1) * s/sqrt(n)
return(c(upper = a + error, mean = a, lower = a - error))
}
-
$\begingroup$ For small sample sizes, this doesn't hold. For example, with the same seed try: x<-rnorm(2,100,15) $\endgroup$– AshtiCommented May 17, 2020 at 17:36
-
$\begingroup$ It does, I'm sorry, I was using the wrong standard deviation. Could please point me to the reference where you found this infomration? $\endgroup$– AshtiCommented May 17, 2020 at 17:40
-
$\begingroup$ @Ashti What information do you mean exactly? The derivation of the formula for the confidence interval? $\endgroup$ Commented May 17, 2020 at 17:41
-
$\begingroup$ The refernce saying what RMISC CI is based on- I couldn't find it when I was searching for it $\endgroup$– AshtiCommented May 17, 2020 at 17:45
-
1$\begingroup$ Thank you so much. This was very helpful $\endgroup$– AshtiCommented May 17, 2020 at 17:48
CI
in R without the parentheses to see the source code). It yields the same result as thet.test
function for one sample. $\endgroup$