Search code examples
rapplyp-valuet-test

How to create dataframe with p-values from a t-test loop across columns in r?


I have two matrices of values for two cohorts across 166 columns representing days (e.g. Day1).

condition_1
        Day1 Day2 Day3 ... Day166
person1 27   38   94       40
person2 69   16   85       47
person3 99   30   90       50
person4 69   88   35       4

and

condition_2
        Day1 Day2 Day3 ... Day166
person1 55   34   17       33
person2 39   77   21       86
person3 98   30   13       71
person4 61   15   29       98

I want to loop a paired t.test() that compares the means for the corresponding day in each condition and creates a new vector with p-values by Day, like this:

     p-value
Day1 0.5
Day2 0.7
Day3 0.88
Day4 0.001

Solution

  • You can try this:

    data.frame(
      "p-value" = sapply(1:166, \(x) t.test(condition_1[,x],condition_2[,x], paired=T)$p.value),
      row.names = paste0("Day",1:166)
    )  
    

    (Note: use function(x) instead of \(x) if you are using R<4.1)

    Output: (first six rows)

              p.value
    Day1   0.60042478
    Day2   0.05388822
    Day3   0.81511287
    Day4   0.16105380
    Day5   0.89930687
    Day6   0.89607922