R:对所有列进行t检验

ery*_*ery 4 r

我试图对我的数据框的所有列(一次两个)进行t检验,并仅提取p值.以下是我的想法:

for (i in c(5:525) ) {

t_test_p.value =sapply( Data[5:525], function(x) t.test(Data[,i],x, na.rm=TRUE)$p.value)

}
Run Code Online (Sandbox Code Playgroud)

我的问题是:1.有没有办法在没有循环的情况下做到这一点?2.如何捕获t检验的结果.

koh*_*ske 16

我建议将您的数据框转换为长格式并使用pairwise.t.test适当的p.adjust:

> library(reshape2)
> 
> df <- data.frame(a=runif(100),
+          b=runif(100),
+          c=runif(100)+0.5,
+          d=runif(100)+0.5,
+          e=runif(100)+1,
+          f=runif(100)+1)
> 
> d <- melt(df)
Using  as id variables
> 
> pairwise.t.test(d$value, d$variable, p.adjust = "none")

    Pairwise comparisons using t tests with pooled SD 

data:  d$value and d$variable 

  a      b      c      d      e   
b 0.86   -      -      -      -   
c <2e-16 <2e-16 -      -      -   
d <2e-16 <2e-16 0.73   -      -   
e <2e-16 <2e-16 <2e-16 <2e-16 -   
f <2e-16 <2e-16 <2e-16 <2e-16 0.63

P value adjustment method: none 
> pairwise.t.test(d$value, d$variable, p.adjust = "bon")

    Pairwise comparisons using t tests with pooled SD 

data:  d$value and d$variable 

  a      b      c      d      e
b 1      -      -      -      -
c <2e-16 <2e-16 -      -      -
d <2e-16 <2e-16 1      -      -
e <2e-16 <2e-16 <2e-16 <2e-16 -
f <2e-16 <2e-16 <2e-16 <2e-16 1

P value adjustment method: bonferroni 
Run Code Online (Sandbox Code Playgroud)


MYa*_*208 15

试试这个吧

X <- rnorm(n=50, mean = 10, sd = 5)
Y <- rnorm(n=50, mean = 15, sd = 6)
Z <- rnorm(n=50, mean = 20, sd = 5)
Data <- data.frame(X, Y, Z)

library(plyr)

combos <- combn(ncol(Data),2)

adply(combos, 2, function(x) {
  test <- t.test(Data[, x[1]], Data[, x[2]])

  out <- data.frame("var1" = colnames(Data)[x[1]]
                    , "var2" = colnames(Data[x[2]])
                    , "t.value" = sprintf("%.3f", test$statistic)
                    ,  "df"= test$parameter
                    ,  "p.value" = sprintf("%.3f", test$p.value)
                    )
  return(out)

})



  X1 var1  var2 t.value       df p.value
1  1   X      Y  -5.598 92.74744   0.000
2  2   X      Z  -9.361 90.12561   0.000
3  3   Y      Z  -3.601 97.62511   0.000
Run Code Online (Sandbox Code Playgroud)


Vin*_*ynd 5

这是另一种解决方案,使用outer.

outer( 
  1:ncol(Data), 1:ncol(Data), 
  Vectorize(
    function (i,j) t.test(Data[,i], Data[,j])$p.value
  ) 
)
Run Code Online (Sandbox Code Playgroud)