当所有值都在一列中时,如何在 R 中执行配对 t 检验?
How to perform a paired t-test in R when all the values are in one column?
在 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 检验?
一些 R 基本函数如何处理从长格式到宽格式的数据:
# 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)
在 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 检验?
一些 R 基本函数如何处理从长格式到宽格式的数据:
# 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)