Jontexas - 27 days ago 7
R Question

# Looping statistic Tests in R

I would like to apply T test in R within a loop

``````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
``````

I tried this code with loop, but it is not working:

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

Can anyone help me with this?
Thanks!

Your code computes 4 t-tests, but the results are lost, because you don't do anything with them. Try the following:

``````info <- read.table(header=TRUE, text="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")

results <- list()
for (i in 2:4){
results[[i]] <- t.test(info[,i] ~ info\$Groups, conf.level = 0.95)
}

print(results)
``````

When interacting with the REPL/console, typing the `t.test` function will compute results and return them. The console will print everything that is returned. In scripts that you `source`, the `t.test` function will return results but they wil not be printed. This is why I put them into a list and printed the list later on.

Btw, I stored your information as `info` not as `table`. R will deal great with variable names that are also function names, but every now and then you will hava a hard time to read error messages, so avoid naming variables `table` or `matrix` or `c` or `df`.

Source (Stackoverflow)