如何从R中的t检验构造表

时间:2017-05-19 10:23:30

标签: r r-markdown t-test

我接受了三次t检验:

Two Sample t-test

data:  cammol by gender
t = -3.8406, df = 175, p-value = 0.0001714
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.11460843 -0.03680225
sample estimates:
mean in group 1 mean in group 2 
       2.318132        2.393837 


Welch Two Sample t-test

data:  alkphos by gender
t = -2.9613, df = 145.68, p-value = 0.003578
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -22.351819  -4.458589
sample estimates:
mean in group 1 mean in group 2 
       85.81319        99.21839 


Two Sample t-test

data:  phosmol by gender
t = -3.4522, df = 175, p-value = 0.0006971
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.14029556 -0.03823242
sample estimates:
mean in group 1 mean in group 2 
       1.059341        1.148605

我想用R markdown构建一个包含这些t检验结果的表,如: wanted_table_format

我已经尝试阅读一些使用“knitr”和“kable”函数的说明,但老实说,我不知道如何将t检验结果应用于这些函数。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

假设您的三个t检验已保存为t1t2t3

t1 <- t.test(rnorm(100), rnorm(100)
t2 <- t.test(rnorm(100), rnorm(100, 1))
t3 <- t.test(rnorm(100), rnorm(100, 2))

您可以使用扫帚和咕噜包将它们转换为一个数据框(然后可以打印成表格):

library(broom)
library(purrr)

tab <- map_df(list(t1, t2, t3), tidy)

在上述数据中,这将成为:

     estimate    estimate1   estimate2  statistic      p.value parameter   conf.low  conf.high
1  0.07889713 -0.008136139 -0.08703327   0.535986 5.925840e-01  193.4152 -0.2114261  0.3692204
2 -0.84980010  0.132836627  0.98263673  -6.169076 3.913068e-09  194.2561 -1.1214809 -0.5781193
3 -1.95876967 -0.039048940  1.91972073 -13.270232 3.618929e-29  197.9963 -2.2498519 -1.6676875
                   method alternative
1 Welch Two Sample t-test   two.sided
2 Welch Two Sample t-test   two.sided
3 Welch Two Sample t-test   two.sided

有些专栏可能对你不重要,所以你可以做这样的事情来获得你想要的专栏:

tab[c("estimate", "statistic", "p.value", "conf.low", "conf.high")]

如评论中所述,您必须先install.packages("broom")install.packages("purrr")