繁体   English   中英

有一个函数t.test()接受R中输入的多个变量

[英]Having a function `t.test()` take multiple variables inputted to it in R

我想知道是否有一种方法可以避免使用t.test() 3次来比较3个变量x1x2x3 ,而不是一次使用t.test()来一次输入两个变量?

例如,对于: x1 = rnorm(20) ; x2 = rnorm(20) ; x3 = rnorm(20) x1 = rnorm(20) ; x2 = rnorm(20) ; x3 = rnorm(20) x1 = rnorm(20) ; x2 = rnorm(20) ; x3 = rnorm(20) ,我现在使用的是: t.test(x1, x2) ; t.test(x1, x3) ; t.test(x2, x3) t.test(x1, x2) ; t.test(x1, x3) ; t.test(x2, x3) t.test(x1, x2) ; t.test(x1, x3) ; t.test(x2, x3)但我可以只使用t.test()吗?

这是我尝试失败的结果:

t.test(cbind(x1, x2, x3))

与您刚才在cor提出的问题类似,这是处理成对计算的语法:

set.seed(21L)
x1 <- rnorm(20); x2 <- rnorm(20); x3 <- rnorm(20)

pcor <- function(...) {
    combn(list(...), 
        2,  
        function(y) cor(y[[1]], y[[2]]),
        simplify=FALSE)
}
pcor(x1, x2, x3)

pttest <- function(...) {
    combn(list(...), 
        2,  
        function(a) t.test(x=a[[1]], y=a[[2]]) #change this to whatever your want
        simplify=FALSE)
}
pttest(x1, x2, x3)

我们可以使用pairwise.t.test

library(dplyr)
library(magrittr)
data(airquality)
airquality %>% 
    mutate(Month = factor(Month, labels = month.abb[5:9])) %>% 
    summarise(pval = list(pairwise.t.test(Ozone, Month, p.adj = "bonf")$p.value)) %>%
    pull(pval) %>%
    extract2(1)
#             May        Jun         Jul         Aug
#Jun 1.0000000000         NA          NA          NA
#Jul 0.0002931151 0.10225483          NA          NA
#Aug 0.0001949061 0.08312222 1.000000000          NA
#Sep 1.0000000000 1.00000000 0.006969712 0.004847635

使用OP的例子

pairwise.t.test(c(x1, x2, x3), rep(paste0("x", 1:3), each = 20), p.adj = "bonf")

#     Pairwise comparisons using t tests with pooled SD 

#data:  c(x1, x2, x3) and rep(paste0("x", 1:3), each = 20) 

#     x1    x2    
# x2 0.486 -    
# x3 1.000 0.095

数据

set.seed(24)
x1 <- rnorm(20) 
x2 <- rnorm(20) 
x3 <- rnorm(20)

如果要随机使用任何变量,请尝试以下操作:

s = sample(x = c("x1","x2","x3"),size = 2,replace = F)
t.test(eval(parse(text=s[1])),eval(parse(text=s[2])))

通过使用成对t检验,必须调整alpha值。 Bonferroni校正常用于农业,Holm有时用于医学。 如果不进行这样的校正,那么它们之间的显着差异将超过其应有的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM