asdfghjkl9999
asdfghjkl9999

Reputation: 53

How to extract lower and upper bounds from confidence level in R from t test function?

I used the following code to retrieve a confidence level for my data:

out <- t.test(my_data$my_col, conf.level = 0.95)
out

This returns something like:

data:  my_data$my_column
t = 30, df = 20, p-value < 2.1e-14
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 62.23191 80.11201
sample estimates:
mean of x 
 75.10457 

I've tried doing:

out[4][1]

But this returns:

$conf.int
[1]  62.23191 80.11201
attr(,"conf.level")
[1] 0.95

How do I specifically get the lower bound and upper bound from this respectively? (i.e. how do I extract 62.23191 and 80.11201 as variables?)

Upvotes: 2

Views: 3529

Answers (2)

te time
te time

Reputation: 495

you can use the broom package not sure if it is more efficient than accepted answer but it is another option.

library(broom)

tidy(t.test(1:10, y = c(7:20),conf.int = TRUE)

 estimate estimate1 estimate2 statistic   p.value parameter conf.low conf.high method                  alternative
     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>    <dbl>     <dbl> <chr>                   <chr>      
1       -8       5.5      13.5     -5.43 0.0000186      22.0    -11.1     -4.95 Welch Two Sample t-test two.sided  

Upvotes: 0

Dave2e
Dave2e

Reputation: 24079

The output from t.test() is a list. The confidence interval is stored as a vector within the $conf.int list element.

To access the individual confidence intervals use out$conf.int[1] & out$conf.int[2]

Example:

out <- t.test(1:10, y=c(7:20)) 
out$conf.int
#[1] -11.052802  -4.947198
#attr(,"conf.level")
#[1] 0.95
out$conf.int[1]
#[1] -11.0528
out$conf.int[2]
#[1] -4.947198

Upvotes: 1

Related Questions