1

我是 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)
 }

此代码运行没有任何错误,但在屏幕上不产生任何输出。我尝试使用“分配”将结果放入变量中,但这会产生错误:

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

4

3 回答 3

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 
于 2013-03-12T19:45:06.540 回答
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)))
于 2013-03-12T19:36:46.533 回答
1

除了“汉森”打印解决方案外,还可以保存和打印结果,如下所示:

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

于 2013-03-12T19:57:29.597 回答