Bade
Bade

Reputation: 747

Store or print results for 't.test' in for loop

I am new to R and having a problem with printing the results of 'for' loop in R. Here is my code:

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

This code runs without any error but produces no output on screen. I tried taking results in a variable using 'assign' but that produces error:

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

Please help me on how can I perform t.test in loop and get their results i.e. print on screen or save in variable.

AK

Upvotes: 1

Views: 9987

Answers (3)

Bade
Bade

Reputation: 747

In addition to 'Hansons' solution of printing, results can be saved and printed like:

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

Upvotes: 1

agstudy
agstudy

Reputation: 121568

I would rewrite your code like this :

I assume your data is like this

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

Then using lapply you can store your result in a list :

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 

Upvotes: 4

Bryan Hanson
Bryan Hanson

Reputation: 6213

In a loop, you need to explicitly print your results in many cases. Try:

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

or

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

Upvotes: 2

Related Questions