Apply t-test on many columns in a dataframe split by factor

前端 未结 3 1128
轻奢々
轻奢々 2020-12-05 16:18

I have a dataframe with one factor column with two levels, and many numeric columns. I want to split the dataframe by the factor column and do t-test on the colunm pairs.

3条回答
  •  [愿得一人]
    2020-12-05 17:05

    Maybe this produces the result you are looking for:

    df <- read.table(text="Group   var1    var2    var3    var4    var5
    1           3   5   7   3   7
    1           3   7   5   9   6
    1           5   2   6   7   6
    1           9   5   7   0   8
    1           2   4   5   7   8
    1           2   3   1   6   4
    2           4   2   7   6   5
    2           0   8   3   7   5
    2           1   2   3   5   9
    2           1   5   3   8   0
    2           2   6   9   0   7
    2           3   6   7   8   8
    2           10  6   3   8   0", header = TRUE)
    
    
    t(sapply(df[-1], function(x) 
         unlist(t.test(x~df$Group)[c("estimate","p.value","statistic","conf.int")])))
    

    The result:

         estimate.mean in group 1 estimate.mean in group 2   p.value statistic.t conf.int1 conf.int2
    var1                 4.000000                 3.000000 0.5635410   0.5955919 -2.696975  4.696975
    var2                 4.333333                 5.000000 0.5592911  -0.6022411 -3.104788  1.771454
    var3                 5.166667                 5.000000 0.9028444   0.1249164 -2.770103  3.103436
    var4                 5.333333                 6.000000 0.7067827  -0.3869530 -4.497927  3.164593
    var5                 6.500000                 4.857143 0.3053172   1.0925986 -1.803808  5.089522
    

提交回复
热议问题