Search code examples
rstatisticssubsett-test

How to run a t-test on a subset of data


First, is this dataset in a tidy form for a t-test?

https://i.sstatic.net/tMK6R.png

Second, I'm trying to do a two sample t-test to compare the means at time 3 of treatment a and b for 'outcome 1'. How would I go about doing this?

Sample data:

df <- structure(list(code = c(100, 100, 100, 101, 101, 101, 102, 102, 
      102, 103, 103, 103), treatment = c("a", "a", "a", "b", "b", "b", 
      "a", "a", "a", "b", "b", "b"), sex = c("f", "f", "f", "m", "m", 
      "m", "f", "f", "f", "f", "f", "f"), time = c(1, 2, 3, 1, 2, 3, 
      1, 2, 3, 1, 2, 3), `outcome 1` = c(21, 23, 33, 44, 45, 47, 22, 
      34, 22, 55, 45, 56), `outcome 2` = c(21, 32, 33, 33, 44, 45, 
      22, 57, 98, 65, 42, 42), `outcome 3` = c(62, 84, 63, 51, 45, 
      74, 85, 34, 96, 86, 45, 47)), .Names = c("code", "treatment", 
      "sex", "time", "outcome 1", "outcome 2", "outcome 3"), 
      class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -12L))

Solution

  • First you'll have to define the subsets you want tested, then you can run the t-test. You don't have to necessarily store the subsets in variables as I've done, but it makes the t-test output clearer.

    Normally with t-test questions, I'd recommend the help provided by ?t.test, but since this involves more complex subsetting, I've included how to do that here:

    var_a <- df$`outcome 1`[df$treatment=="a" & df$time==3]
    var_b <- df$`outcome 1`[df$treatment=="b" & df$time==3]
    
    t.test(var_a,var_b)
    

    Output:

        Welch Two Sample t-test
    
    data:  var_a and var_b
    t = -3.3773, df = 1.9245, p-value = 0.08182
    alternative hypothesis: true difference in means is not equal to 0
    95 percent confidence interval:
     -55.754265   7.754265
    sample estimates:
    mean of x mean of y 
         27.5      51.5