Is there an easier way to write a function like this to calculate the confidence interval?

While writing a little function to calculate the 99% confidence interval of some sample,

I get a different answer than the R t.test formula. Here's my function:

confinterval <- function(x,alpha){
  alpha = 0.01
  df = length(x)-1
  pos_confinterval = mean(x) + qt((1 - alpha/2),df)*(var(x)/length(x))
  neg_confinterval = mean(x) - qt((1 - alpha/2),df)*(var(x)/length(x))

  cut_points <- c(neg_confinterval,pos_confinterval)
  return(cut_points)
}

confinterval(data) gives me the following vector of cutpoints (4.469488 4.598704) While : t.test(data,conf.level=.995) yields (4.064382 5.003810)

Is there an easier way to get a function like this to calculates confidence intervals?

Upvotes: 0

Views: 424

Answers (1)

Aaron Montgomery
Aaron Montgomery

Reputation: 1407

(Aside: Do you mean to have the line alpha = 0.01 as part of your function? I assume that 0.01 should just be passed in as a parameter value when the function is called, right?)

You're getting a different answer than t.test because you need a square root on the object you're multiplying by the t-distribution critical value. If you wrap var(x) / length(x) inside sqrt, you'll get the same result as t.test.

You can also use as.numeric(t.test(x, conf.level = 0.99)$conf.int) to directly access the result from the t.test function.

Upvotes: 2

Related Questions