11 Hypothesis Testing

In this chapter, we will cover how to conduct a t-test of means and chi-square test of frequencies.

11.1 t-test

To conduct a t-test, we use the t.test() function. What we input into this function depends on whether we want to compute a one-sample or two-sample test.

11.1.1 One-sample t-test

To conduct a 1-sample t-test, we pass a vector and a mu value into the t.test() function. The mu value is the number against which we will compare the vector’s mean to determine whether there is a statistically significant difference.

# Testing whether the mean MPG is statistically equal to 17.
t.test(mtcars$mpg, mu = 17)
## 
##  One Sample t-test
## 
## data:  mtcars$mpg
## t = 2.9008, df = 31, p-value = 0.006788
## alternative hypothesis: true mean is not equal to 17
## 95 percent confidence interval:
##  17.91768 22.26357
## sample estimates:
## mean of x 
##  20.09062

11.1.2 Two-sample t-test

To conduct a two-sample t-test, we use the formula syntax of y ~ x, where y is our continuous dependent variable and x is our categorical independent variable. Then, we pass this formula into t.test().

# Compare mean MPG by transmission type
with(mtcars, t.test(mpg ~ am))
## 
##  Welch Two Sample t-test
## 
## data:  mpg by am
## t = -3.7671, df = 18.332, p-value = 0.001374
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -11.280194  -3.209684
## sample estimates:
## mean in group 0 mean in group 1 
##        17.14737        24.39231

11.2 Chi-square test

To conduct a Chi-square test, we pass a two-way table into the chisq.test() function.

mytable <- with(mtcars, table(gear, am))

mytable
##     am
## gear  0  1
##    3 15  0
##    4  4  8
##    5  0  5
chisq.test(mytable)
## Warning in chisq.test(mytable): Chi-squared approximation may be incorrect
## 
##  Pearson's Chi-squared test
## 
## data:  mytable
## X-squared = 20.945, df = 2, p-value = 2.831e-05

11.3 Summary

Table 11.1: Summary of Hypothesis Testing
Function Description Example
t.test(x, mu) Test of mean against mu. t.test(mtcars$mpg, mu = 17)
t.test(y ~ x) Test of group means. with(mtcars, t.test(mpg ~ am))
chisq.test(table) Test of two-way frequencies. with(mtcars, chisq.test(table(gear, am)))