Skip to content
Prev 118787 / 398498 Next

warning in a loop

You can investigate what's gone wrong after the loop has failed by looking
at the values of i, k, p, and t. Although d[(d[,(i+1)]%in%1),1] produces a
vector, k has only one element. Same with p. Should then be obvious why the
t.test produces an error.

The problem is with the [i] index for k and p; take those away and it works.
If you want to keep the values generated in the loop, make k and p lists and
index with k[[i]] and p[[i]].


A better way to do this would be to use 'sample' to randomize the measured
values in d[,1] and then use d[,2] to group them for testing. You can then
use hundreds of iterations:

t <- rep(NA, 999) 
for(i in 1:999) {
   samp <- sample(d[,1])
   t <- t.test(samp[d[,2]==1], samp[d[,2]==2])$p.value
}
sum(t < 0.05)  # How many were 'significant'?

Note that I prefer to use t <- rep(NA,...) to allocate space, rather than
1:999, so that NA appears as the result if there's a problem.

Why not just do a randomization test?

t <- rep(NA, 1000)
t[1] <- mean(d[d[,2]==1,1]) - mean(d[d[,2]==2,1]) # This is the observed
difference in means
for(i in 2:1000) {
   samp <- sample(d[,1])
   t[i] <- mean(samp[d[,2]==1]) - mean(samp[d[,2]==2])
}
t <- abs(t)   # Skip this line if you want a 1-sided test
sum(t >= t[1])/1000  # This is the 'p-value'

HTH, Mike.
Tavpritesh Sethi wrote: