0

I did a thoroughly for the answer of this question but I found nothing.

Assume that I have two samples of paired observations with sample size 4. My goal is to perform an exact permutation set to compare the sample means, and to carry out that procedure I need to generate all the possible pair permutations, i.e. I have to generate 16 different permutations (2 possibilities for the first pair, two for the second... and so on).

That is, if my samples are:

#samples
x <- rnorm(4,0,1)
y <- rnorm(4,5,1)

#statistic over the original samples
dif0 <- mean(x) - mean(y)

I can generate all the possible permutations using 4 nested "for" loops, as follows:

d1 < c()
d2 <- c()
samp_ab <- data.frame("x"=x,"y"=y)
ind <- 1:2
for (i1 in 1:2) 
{
    d1[1] <- samp_ab[1,ind[i1]]  
    d2[1] <- samp_ab[1,ind[-i1]] 
    for (i2 in 1:2) {  
        d1[2] <- samp_ab[2,ind[i2]]  
        d2[2] <- samp_ab[2,ind[-i2]] 
        for (i3 in 1:2) {  
            d1[3] <- samp_ab[3,ind[i3]]  
            d2[3] <- samp_ab[3,ind[-i3]]  
            for (i4 in 1:2) { #loop4
                d1[4] <- samp_ab[4,ind[i4]]  
                d2[4] <- samp_ab[4,ind[-i4]]  

                #compute the statistic
                k = k + 1 #counter
                S[k] <- mean(d1) - mean(d2)
            }
        }
    }
}   

There is any possibility for this code to be simplified? I thought about a function that "writes" the nested loops and then executes it... but I have no idea how to do it. I would like to obtain a general procedure for paired samples (or even for combining three elements) without writting many nested loops. For instance, I had to do it with n=10, which resulted in 10 loops... just to create 1024 (2^10) permutations.

Many thanks in advance.

Bob__
  • 12,361
  • 3
  • 28
  • 42

1 Answers1

0

This appears to be R, with which I am unfamiliar, but for a permutation you want a Cartesian product. Check out the below solutions:

Cartesian product data frame in R

How to do cross join in R?

Community
  • 1
  • 1
Moho
  • 15,457
  • 1
  • 30
  • 31