我有以下数据:
df<-read.table(text=" A1 A2 A3 A4 A5 B1 B2 B3 B4 B5
F M F M F 17 15 14 17 18
M M F M F 17 15 12 18 14
F M F M F 16 12 17 18 16
F M F M F 13 13 15 17 18
F M F M F 14 15 17 14 14
M M F F F 18 14 15 17 18
F M F F F 16 12 15 17 20
M F F F F 12 12 18 13 17
F F F F F 14 12 12 19 16
M F F F F 18 14 13 12 14
F F F F F 19 15 14 15 18
F F F M F 14 20 13 15 19
F F F M M 18 20 19 13 19
M F F M M 15 15 12 16 19
F M M M M 18 14 13 18 18
F M M M M 17 12 12 13 19
F M M F M 12 12 13 13 16
M M M F M 14 19 15 20 14
F M M F M 18 12 12 12 14", h=T)
我想对组使用以下功能进行t检验。例如A1和B1:
t.test(B1~A1, data=df)
ggplot(df, aes(x=B1, y=A1)) +
geom_boxplot()
现在,我想使用循环使用上面的t测试函数来获取所有数据的输出,即A1与B1,A2与B2,A3与B3,A4与B4和A5与B5和...我将从t检验中得到5个输出。
谢谢您的帮助
答案 0 :(得分:3)
我们可以使用Map
在list
中相应的“ A”,“ B”列之间创建公式,并应用t.test
Map(function(x, y) t.test(reformulate(x, y), data = df),
names(df)[1:5], names(df)[6:10])
也可以使用paste
创建公式,并使用formula
换行
Map(function(x,y) t.test(as.formula(paste0(y, "~", x)),
data = df), names(df)[1:5], names(df)[6:10])
如果我们需要箱线图
library(purrr)
library(ggplot2)
map2(names(df)[6:10], names(df)[1:5], ~
ggplot(df, aes(x = !!rlang::sym(.x), y = !!rlang::sym(.y))) +
geom_boxplot())