Search code examples
rpermutationsample

Is there a way to create a permutation of a vector without using the sample() function in R?


I hope you are having a nice day. I would like to know if there is a way to create a permutation (rearrangement) of the values in a vector in R?

My professor provided with an assignment in which we are supposed create functions for a randomization test, one while using sample() to create a permutation and one not using the sample() function. So far all of my efforts have been fruitless, as any answer that I can find always resorts in the use of the sample() function. I have tried several other methods, such as indexing with runif() and writing my own functions, but to no avail. Alas, I have accepted defeat and come here for salvation.

While using the sample() function, the code looks like:

#create the groups
a <- c(2,5,5,6,6,7,8,9)
b <- c(1,1,2,3,3,4,5,7,7,8)

#create a permutation of the combined vector without replacement using the sample function()
permsample <-sample(c(a,b),replace=FALSE)

permsample
[1] 2 5 6 1 7 7 3 8 6 3 5 9 2 7 4 8 1 5

And, for reference, the entire code of my function looks like:

PermutationTtest <- function(a, b, P){
  sample.t.value <- t.test(a, b)$statistic
  perm.t.values<-matrix(rep(0,P),P,1)
  N <-length(a)
  M <-length(b)
  for (i in 1:P)
  {
    permsample <-sample(c(a,b),replace=FALSE)
    pgroup1 <- permsample[1:N]
    pgroup2 <- permsample[(N+1) : (N+M)]
    perm.t.values[i]<-  t.test(pgroup1, pgroup2)$statistic
  }
  return(mean(perm.t.values))
}

How would I achieve the same thing, but without using the sample() function and within the confines of base R? The only hint my professor gave was "use indices." Thank you very much for your help and have a nice day.


Solution

  • You can use runif() to generate a value between 1.0 and the length of the final array. The floor() function returns the integer part of that number. At each iteration, i decrease the range of the random number to choose, append the element in the rn'th position of the original array to the new one and remove it.

    a <- c(2,5,5,6,6,7,8,9)
    b <- c(1,1,2,3,3,4,5,7,7,8)
    
    c<-c(a,b)
    
    index<-length(c)
    perm<-c()
    
    for(i in 1:length(c)){
      rn = floor(runif(1, min=1, max=index))
      perm<-append(perm,c[rn])
      c=c[-rn]
      index=index-1
    }