R中的循环统计测试

时间:2016-11-06 04:07:56

标签: r loops statistics

我想在循环中在R中应用T测试

Groups  Length  Size    Diet    place
A   2.4048381   0.7474989   1.6573392   334.3273456
A   2.72500485  0.86392165  1.8610832   452.5593152
A   1.396782867 0.533330367 0.8634525   225.5998728
B   1.3888505   0.46478175  0.92406875  189.9576476
B   1.38594795  0.60068945  0.7852585   298.3744962
B   2.53491245  0.95608005  1.5788324   303.9052525

我用循环尝试了这段代码,但它无法正常工作:

for (i in 2:4){
  t.test(table[,c(i)] ~ table$Groups, conf.level = 0.95)
}

任何人都可以帮我吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

使用apply功能,您也可以这样做:

res<- cbind(
do.call(rbind,apply(info[,-1],2,function(cv)t.test(cv ~ info$Groups, conf.level = 0.95)
                    [c("statistic","parameter","p.value")]))
,
t(apply(info[,-1],2,function(cv)unlist(t.test(cv ~ info$Groups, conf.level = 0.95)
                    [c("conf.int","estimate")])))
)
res


> res
       statistic parameter p.value   conf.int1  conf.int2 estimate.mean in group A estimate.mean in group B
Length 0.7327329 3.991849  0.5044236 -1.13263   1.943907  2.175542                 1.769904                
Size   0.2339013 3.467515  0.8282072 -0.47739   0.5595231 0.714917                 0.6738504               
Diet   0.9336103 3.823748  0.4056203 -0.7396173 1.468761  1.460625                 1.096053                
place  0.9748978 3.162223  0.398155  -159.4359  306.2686  337.4955                 264.0791