应用两个不同矩阵-R代码的列的配对t检验

时间:2012-06-30 01:35:15

标签: r

我有两个矩阵。我想逐列应用配对t检验列,并打印每列的t值,自由度,置信区间和p值。我从下面的代码开始。

D1和D2是两个矩阵:

for (j in 1:n){
    t.test(D1[,j],D2[,j],paired=T)
}

另外,如何打印此循环中的每个结果?

1 个答案:

答案 0 :(得分:7)

以下是我解决问题的方法:

#Make some random data
m1 <- matrix(rnorm(100), ncol = 5)
m2 <- matrix(rnorm(100), ncol = 5)

#Define a function to run your t.test, grab the relevant stats, and put them in a data.frame
f <- function(x,y){
  test <- t.test(x,y, paired=TRUE)
  out <- data.frame(stat = test$statistic,
                    df   = test$parameter,
                    pval = test$p.value,
                    conl = test$conf.int[1],
                    conh = test$conf.int[2]
                    )
  return(out)
}

#iterate over your columns via sapply
sapply(seq(ncol(m1)), function(x) f(m1[,x], m2[,x]))
#-----
     [,1]       [,2]       [,3]       [,4]       [,5]      
stat -0.7317108 1.73474    -0.0658436 0.6252509  -0.6161323
df   19         19         19         19         19        
pval 0.4732743  0.09898052 0.9481902  0.5392442  0.5451188 
conl -1.097654  -0.1259523 -0.7284456 -0.5680937 -0.7523431
conh 0.5289878  1.345625   0.6840117  1.052094   0.4101385

您可能想要转置输出,因为它是列主要有序。