animus
animus

Reputation: 77

Perform Permutations of a categorical variable in R

The dataset I have resembles something like this

dd = data.frame(X = factor(c("p","p","p","p","s","s","s"), 
                           levels = c("p","s")),
                Y = factor(c("ns","ns","ss","ss","ss","vs","vs"), 
                           levels = c("ns","ss","vs"))
                )

I need to fix Y and permute X. Total permutations are 7C3 = 35.
I tried to use the function: sample, but the only way I can do it is run the sample for 10000 times and take unique vectors
Is there a better way to do this? The above method will only work if there are small number of total permutations.
Can anyone help me figure this out?

This is the code I used to create the 35 vectors

get_perm <- function(x){
  #This will work up to n = 6
  n = length(x)
  nperm = 10000
  all_samp = matrix(NA, nrow = nperm, ncol = n)
  for(i in 1:nperm){
    set.seed(i)
    all_samp[i,] = sample(x)
  }
  return(unique(all_samp))
}

X_perm = get_perm(dd$X)

Upvotes: 0

Views: 374

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101327

Do you mean something like below using permutations from package gtools + unique

library(gtools)
with(
  dd,
  unique(permutations(length(X), length(X), as.integer(X), set = FALSE))
)

which gives

      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    2    2    2    1    1    1    1
 [2,]    2    2    1    2    1    1    1
 [3,]    2    2    1    1    2    1    1
 [4,]    2    2    1    1    1    2    1
 [5,]    2    2    1    1    1    1    2
 [6,]    2    1    2    2    1    1    1
 [7,]    2    1    2    1    2    1    1
 [8,]    2    1    2    1    1    2    1
 [9,]    2    1    2    1    1    1    2
[10,]    2    1    1    2    2    1    1
[11,]    2    1    1    2    1    2    1
[12,]    2    1    1    2    1    1    2
[13,]    2    1    1    1    2    2    1
[14,]    2    1    1    1    2    1    2
[15,]    2    1    1    1    1    2    2
[16,]    1    2    2    2    1    1    1
[17,]    1    2    2    1    2    1    1
[18,]    1    2    2    1    1    2    1
[19,]    1    2    2    1    1    1    2
[20,]    1    2    1    2    2    1    1
[21,]    1    2    1    2    1    2    1
[22,]    1    2    1    2    1    1    2
[23,]    1    2    1    1    2    2    1
[24,]    1    2    1    1    2    1    2
[25,]    1    2    1    1    1    2    2
[26,]    1    1    2    2    2    1    1
[27,]    1    1    2    2    1    2    1
[28,]    1    1    2    2    1    1    2
[29,]    1    1    2    1    2    2    1
[30,]    1    1    2    1    2    1    2
[31,]    1    1    2    1    1    2    2
[32,]    1    1    1    2    2    2    1
[33,]    1    1    1    2    2    1    2
[34,]    1    1    1    2    1    2    2
[35,]    1    1    1    1    2    2    2

Upvotes: 1

Related Questions