Independent-samples t-test

Example RQ and data

RQ: Do first-generation university students report significantly different mean levels of academic self-efficacy compared to continuing-generation students?

Here’s what the first six rows of the data looks like:

head(ase_data)
# A tibble: 6 × 3
  student_num generation   ase
        <int> <chr>      <dbl>
1           2 First         47
2           3 Continuing    44
3           4 Continuing    20
4           5 Continuing    38
5           6 First         16
6           7 Continuing    33

A higher ASE score represents better academic self-efficacy.

Here’s how we might plot this data (if you’re not sure what part of the code does, delete it or comment it out and try running what’s leftover to see what changes):

ase_data |>
  ggplot(aes(x = generation, y = ase)) +
  geom_violin() +
  geom_jitter(height = 0, alpha = 0.5) +
  stat_summary(fun = mean, geom = 'point', size = 5) +
  labs(
    y = 'Academic Self-Efficacy score',
    x = 'Generation'
  )

Define hypotheses

The null hypothesis is that there’s no difference between the mean ASE scores of continuing-generation students and first-generation students. Formally:

\[ H_0 : \mu_\text{Continuing} = \mu_\text{First} \]

Based on our research question, our alternative hypothesis is directional: we want to know whether first-generation students have lower ASE than continuing-generation students. Or, flipping these around into alphabetical order (which we’ll need to do in t.test() below), we want to know whether continuing gneeration students have greater ASE than first-generation students. Formally:

\[ H_1 : \mu_\text{Continuing} > \mu_\text{First} \]

To write these hypotheses in plain text in your R script, you can write:

# H0: mu_Continuing = mu_First
# H1: mu_Continuing < mu_First

The useful symbols for your alternative hypothesis are < (less than), > (greater than), and != (not equal to).

Run the test

Use the function t.test(), and give it five pieces of information:

  • the data we want to test, formatted as: <dependent variable> ~ <grouping> (usually we name a column of the data frame using dollar sign notation; see the Subset a dataframe flash card)
  • mu = the difference we would expect between groups if the null hypothesis were true, that is, zero
  • alternative = two.sided, less, or greater; the direction of the \(H_1\)
    • To choose between less or greater, think of the levels of the grouping variable in alphabetical order.
    • For example, the alternative hypothesis \(\mu_B > \mu_A\) must be entered as alternative = 'less', because A (the alphabetically first level) is hypothesised to be less than B (the alphabetically second level).
  • var.equal = TRUE imposes the assumption of equal variance (see below).
  • conf.level = 1 minus our \(\alpha\) level; in Psychology, this will nearly always be .95.
t.test(
  ase_data$ase ~ ase_data$generation,
  # asks: how is ASE different for each level of generation?
  alternative = 'greater',
  mu = 0,
  var.equal = TRUE,
  conf.level = .95
)

    Two Sample t-test

data:  ase_data$ase by ase_data$generation
t = 1.22, df = 20, p-value = 0.12
alternative hypothesis: true difference in means between group Continuing and group First is greater than 0
95 percent confidence interval:
 -3.0441     Inf
sample estimates:
mean in group Continuing      mean in group First 
                  34.909                   27.545 

Assumptions we must make

Type of constraint What to check for an independent-samples t-test
Data requirements The dependent variable is numeric.
Assumption of independence The obtained sample data are a random sample from the population of interest, both within and across groups.
Assumption of normality The sampling distribution of sample means in each group is normally distributed.
Assumption of equal variance The population variance is the same for both groups.

Data requirements

The dependent variable should be interval, ratio, or integer data (that is, numeric).

The ase variable is indeed numeric:

ase_data$ase
 [1] 47 44 20 38 16 33 17 27 38 19 38 24 30 32 10  9 37 47 42  9 54 56

Assumption of independence

The obtained sample data are a random sample from the population of interest, both within and across groups.

Essentially this means: overall, the data was sampled randomly from the wider population of interest, and also people in each group were randomly sampled from their corresponding smaller populations.

This is an issue of study design more than something we can check directly.

But we can still check the data for problems that indicate non-independence between groups:

  • Does each individual who contributed data belong to only one group? (In this case, yes.)
  • Does each individual have only one observation in the group they belong to? (In this case, yes.)

Assumption of normality

The sampling distribution of sample means in each group is normally distributed.

We can’t check this directly, because we don’t know the population. But we can check the normality of our given sample. If it matches a normal distribution pretty well, then so will the sampling distribution of sample means.

Check with a Q-Q plot:

ase_data |>
  ggplot(aes(sample = ase)) +
  geom_qq() +
  geom_qq_line() +
  facet_wrap(~ generation) +
  labs(
    x = "Theoretical quantiles",
    y = 'Sample quantiles'
  ) 

Both groups’ data matches the theoretical normal distribution quite well.

TipExamples of “sufficiently normal” Q-Q plots

All of the Q-Q plots below show data that is sampled from different normal distributions. So all the plots below should be considered normal “enough”.

Code
library(patchwork)

sim_normal <- function(){
  
  # randomly sample from a uniform distribution some parameter values
  n_obs <- round(runif(1, min = 20, max = 40))
  mean <- runif(1, min = -10, max = 10)
  sd <- abs(mean * round(runif(1, min = 1, max = 10)))
  # ^ multiply SD by mean to get variability of the right magnitude
  
  # simulate the data
  df <- tibble(
    x = rnorm(n_obs, mean = mean, sd = sd)
  )
  return(list(df)) # return as list so we end up with a list of dfs
}

make_qq <- function(dat){
  # dat must contain continuous variable x
  
  dat |>
    ggplot(aes(sample = x)) +
    geom_qq() +
    geom_qq_line() +
    labs(
      x = "Theoretical quantiles",
      y = 'Sample quantiles'
    )
}


set.seed(2)  # so your random numbers are the same as my random numbers

# generate set number of normally distributed datasets
dfs <- replicate(12, sim_normal())

# use patchwork's wrap_plots() to combine each dataset's qq plot into a single graphic
wrap_plots( sapply(dfs, make_qq) ) +
  plot_layout(axes = "collect")  # use only one axis label

(You don’t need to understand the code that created this graphic unless you want to.)

Assumption of equal variance

The population variance is the same for both groups.

Again, we don’t know what the population variance looks like. But we can eyeball the variance in each of our independent samples and, if the variance appears sufficiently similar, then we can make this assumption.

We’ll visualise each variable’s variability using density plots. We want the spread of the density plots to be roughly the same.

ase_data |>
  ggplot(aes(x = ase)) +
  geom_density() +
  geom_rug() +  # adds a tick above the x axis for each data point
  facet_wrap(~ generation, nrow = 2)  # nrow=2 stacks the facets

The horizontal spread of these density plots looks similar enough to me.

TipExamples of “sufficiently equal variance” density plots

All of the density plots below show pairs of samples that are both drawn from populations with equal variance. So all the plots below show pairs of samples which should be considered to have equal “enough” variance.

Code
library(patchwork)

sim_normal <- function(){
  
  # randomly sample from a uniform distribution some parameter values
  n_obs <- round(runif(1, min = 10, max = 30))
  mean <- runif(1, min = -10, max = 10)
  sd <- abs(mean * runif(1, min = 1, max = 10))
  # ^ multiply SD by mean to get variability of the right magnitude
  
  # draw two samples, each of size n_obs, from this population
  df <- tibble(
    x = rnorm(n_obs*2, mean = mean, sd = sd),
    g = c(
      rep('A', n_obs),
      rep('B', n_obs)
    )
  )
  return(list(df)) # return as list so we end up with a list of dfs
}

make_dens <- function(dat){
  # dat must contain continuous variable x and categ variable g
  dat |>
    ggplot(aes(x = x)) +
    geom_density() +
    geom_rug() +  # adds a tick above the x axis for each data point
    facet_wrap(~ g, nrow = 2) +  # nrow=2 stacks the facets
    theme(
      plot.margin = margin_auto(1, unit = "cm"),
    )
}


set.seed(2)  # so your random numbers are the same as my random numbers

# generate set number of normally distributed datasets
dfs <- replicate(6, sim_normal())

# use patchwork's wrap_plots() to combine each dataset's qq plot into a single graphic
wrap_plots( sapply(dfs, make_dens) ) +
  plot_layout(axes = "collect")  # use only one axis label

(You don’t need to understand the code that created this graphic unless you want to.)

Calculate effect size

For t-tests, the appropriate measure of standardised effect size is Cohen’s D.

To compute this in R, first attach the effectsize package:

library(effectsize)

This package gives us the function cohens_d(). Give it the exact same arguments you’d give t.test() (see above):

cohens_d(
  ase_data$ase ~ ase_data$generation,
  alternative = 'greater',
  mu = 0,
  var.equal = TRUE,
  conf.level = .95
)
Cohen's d |       95% CI
------------------------
0.52      | [-0.20, Inf]

- Estimated using pooled SD.
- One-sided CIs: upper bound fixed at [Inf].

Interpreting Cohen’s D

  • Small or weak effect: around 0.2 (whether positive or negative)
  • Medium or moderate effect: around 0.5 (whether positive or negative)
  • Large or strong effect: around 0.8 or greater (whether positive or negative)

Example write-up

First, compute some additional descriptive statistics that we’ll need:

ase_data |>
  group_by(generation) |>
  summarise(
    M  = mean(ase),
    SD = sd(ase),
    N  = n()
  )
# A tibble: 2 × 4
  generation     M    SD     N
  <chr>      <dbl> <dbl> <int>
1 Continuing  34.9  14.6    11
2 First       27.5  13.7    11


Now we’re ready to write up all the results together.

We wanted to find out whether first-generation university students report lower Academic Self-Efficacy (ASE) compared to continuing-generation university students. We therefore conducted an independent-samples t-test with \(\alpha\) = .05 to compare ASE scores in these two groups. ASE scores can range from 9 to 63, and higher scores indicate greater academic self-efficacy.

The independent-samples t-test’s data requirements are met: the dependent variable is numeric. We are also willing to assume that our data was independently sampled from a population that is normally-distributed and that has equal variance in both groups. Based on the study design, our observations were sampled sufficiently independently. And based on a Q-Q plot, our sample is sufficiently normally distributed. Finally, based on density plots of each group’s distribution, both groups appear to have sufficiently equal variance.

Turning to the test results: although we observed a lower mean ASE score for first-generation students (N = 11, M = 27.5, SD = 13.7) than for continuing-generation students (N = 11, M = 34.9, SD = 14.6), the t-test indicated no statistically significant difference between the two groups (t(20) = 1.22, p = .12, one-sided).


(Note on why no Cohen’s D here: we failed to reject H0 in this test, which means that potentially there’s no actual effect which would have a size we could measure. So when we have a non-significant test result, we don’t report Cohen’s D.)

TipReporting the results of a statistical test

The most important thing: Your decision about the null hypothesis should be clear.

You can make sure your decision is clear either by

  • stating that you reject/fail to reject H0, or
  • stating that the result is significant or not.