在for循环中存储或打印't.test'的结果

时间:2013-03-12 19:32:00

标签: r for-loop

我是R的新手,在R中打印'for'循环的结果时出现问题。这是我的代码:

afile <- read.table(file = 'data.txt', head =T)##Has three columns Lab, Store and Batch
lab1 <- afile$Lab[afile$Batch == 1]
lab2 <- afile$Lab[afile$Batch == 2]
lab3 <- afile$Lab[afile$Batch == 3]
lab_list <- list(lab1,lab2,lab3)
for (i in 1:2){
    x=lab_list[[i]]
    y=lab_list[[i+1]]
    t.test(x,y,alternative='two.sided',conf.level=0.95)
 }

此代码运行时没有任何错误,但在屏幕上没有输出。我尝试使用'assign'在变量中获取结果但产生错误:

for (i in 1:2){x=lab_list[[i]];y=lab_list[[i+1]];assign(paste(res,i,sep=''),t.test(x,y,alternative='two.sided',conf.level=0.95))}
Warning messages:
1: In assign(paste(res, i, sep = ""), t.test(x, y, alternative = "two.sided",  :
only the first element is used as variable name
2: In assign(paste(res, i, sep = ""), t.test(x, y, alternative = "two.sided",  :
only the first element is used as variable name

请帮助我如何在循环中执行t.test并获得结果,即在屏幕上打印或保存在变量中。

AK

3 个答案:

答案 0 :(得分:4)

我会像这样重写你的代码:

我假设你的数据是这样的

afile <- data.frame(Batch= sample(1:3,10,rep=TRUE),lab=rnorm(10))
afile
   Batch        lab
1      2  0.4075675
2      1  0.3006192
3      1 -0.4824655
4      3  1.0656481
5      1  0.1741648
6      2 -1.4911526
7      2  0.2216970
8      1 -0.3862147
9      1 -0.4578520
10     1 -0.6298040

然后使用lapply,您可以将结果存储在列表中:

lapply(1:2,function(i){
 x <- subset(afile,Batch==i)
 y <- subset(afile,Batch==i+1)
   t.test(x,y,alternative='two.sided',conf.level=0.95)
})

[[1]]

    Welch Two Sample t-test

data:  x and y 
t = -0.7829, df = 6.257, p-value = 0.4623
alternative hypothesis: true difference in means is not equal to 0 
95 percent confidence interval:
 -1.964637  1.005008 
sample estimates:
mean of x mean of y 
0.3765373 0.8563520 


[[2]]

    Welch Two Sample t-test

data:  x and y 
t = -1.0439, df = 1.797, p-value = 0.4165
alternative hypothesis: true difference in means is not equal to 0 
95 percent confidence interval:
 -6.588720  4.235776 
sample estimates:
mean of x mean of y 
 0.856352  2.032824 

答案 1 :(得分:2)

在循环中,您需要在许多情况下明确打印结果。尝试:

print(t.test(x,y,alternative='two.sided',conf.level=0.95))

print(summary(t.test(x,y,alternative='two.sided',conf.level=0.95)))

答案 2 :(得分:1)

除了&#39; Hansons&#39;打印解决方案,结果可以保存和打印如下:

result <- vector("list",6)
for (i in 1:5){x=lab_list[[i]];y=lab_list[[i+1]];result[[i]] = t.test(x,y,alternative='two.sided',conf.level=0.95)}
result

AK