Section 24 Hypothesis Testing - Two Samples: t.test


24.1 Two Samples, Unknown Variance

The R function t.test peforms one and two sample t-tests on vectors of data.

?t.test

24.2 Arguments

Arguments Explanation
x a (non-empty) numeric vector of data values.
y an optional (non-empty) numeric vector of data values.
alternative a character string specifying the alternative hypothesis, must be one of two.sided (default), greater or less. You can specify just the initial letter.
mu a number indicating the true value of the mean (or difference in means if you are performing a two sample test).
paired a logical indicating whether you want a paired t-test.
var.equal a logical variable indicating whether to treat the two variances as being equal. If TRUE then the pooled variance is used to estimate the variance otherwise the Welch (or Satterthwaite) approximation to the degrees of freedom is used.
conf.level confidence level of the interval.
formula a formula of the form lhs ~ rhs where lhs is a numeric variable giving the data values and rhs a factor with two levels giving the corresponding groups.
data an optional matrix or data frame (or similar
subset an optional vector specifying a subset of observations to be used.
na.action a function which indicates what should happen when the data contain NAs. Defaults to getOption(na.action).


24.3 Example

  • Save the mtcars data into a new dataset named mtc

  • Check the types of variables

  • Convert the variable am as a factor

  • Do simple summary statistics and plots to find the relationship between mpg and am

  • Use the R function t.test to test if the mean mpg is different between automatic and manual transmission.

mtc <- mtcars

# Variable 'am'

mtc$am <- as.factor(mtc$am)

with(data=mtc, tapply(X = mpg, INDEX = am, FUN = mean, na.rm=TRUE))

with(data=mtc, tapply(X = mpg, INDEX = am, FUN = sd, na.rm=TRUE))

plot(mpg ~ am, data=mtc)

t.test(mpg ~ am, data=mtc, 
       alternative='two.sided', 
       paired=FALSE, var.equal = FALSE, 
       conf.level = 0.95)


24.4 Exercise 1

  • Use the mtcar data to test if the mean mpg is different between V engine or a straight engine (variable vs). Conduct appropriate summary statistics, apply t test and draw your conclusion.


24.5 Exercise 2

  • Read the weather data

  • Test if the mean temp, humidity and windsp were different between the Dry and Wet day.

  • Conduct appropriate summary statistics, apply t test and draw your conclusion.