当所有值都在一列中时,如何在R中执行配对t检验?

时间:2018-09-22 22:23:26

标签: r t-test

用于在R中执行成对t检验的数据帧的常见格式是分为两列的给定度量,因此每一行表示同一主题或个人。 例如:

 > #     Before     After
    > #1      31        32
    > #2      22        34
    > #3      41        35

但是,在数据框中显示数据并不总是这种情况。

我有一个数据帧,其结构非常常见,看起来像这样:

 subject <- c("A1", "A2" ,"A1" ,"A3" ,"A3" ,"A2")
    value <- c(34, 43, 25, 43, 54, 22)
    group <- c("before", "after", "after", "after", "before", "before")

    mydata <- data.frame(subject, value, group)

    #  subject value  group
    #1      A1    34 before
    #2      A2    43  after
    #3      A1    25  after
    #4      A3    43  after
    #5      A3    54 before
    #6      A2    22 before

那么,基于此数据框,我如何在R中执行双向配对t检验?

1 个答案:

答案 0 :(得分:2)

What about some R base function to have data from long to wide format:

# reshape from long to wide
mydata_wide <- reshape(mydata, idvar = "subject", timevar = "group", direction = "wide")

# rename columns
colnames(mydata_wide)[2] <-"before"
colnames(mydata_wide)[3] <-"after"

mydata_wide
  subject before after
1      A1     34    25
2      A2     22    43
4      A3     54    43

# t-test
 t.test(mydata_wide$before,
       mydata_wide$after,
       paired=TRUE,
       conf.level=0.95)