melbez
melbez

Reputation: 1000

Showing all possible combinations of categories with restrictions in R

I have the following 9 categories, which represent different conditions in an experiment. In reality, I have 25 different conditions, but I am only showing 9 for simplicity.

   1   2   3
A  A1  A2  A3
B  B1  B2  B3
C  C1  C2  C3

Each person will see 3 of the categories. They will see each letter (A, B, C) once and will see each number (1, 2, 3) once. The order matters.

For example, if they randomly see A1 first, then the second category they see can be B2, B3, C2, or C3. If they see C3 for the second category, then the only remaining option for the third category is B2. Another example: if they randomly see C2 first, then they can see B1, B3, A1, or A3 second. If they see A1 second, they must see B3 third.

My goal is to create an efficient way to find all possible ways of presenting participants with 3 categories while adhering to the rules I have laid out. I know how to do this manually, but I assume there is a better way in R. I just don't know where to start. Do you have any recommendations for how I could begin to set this up?

Here's some pseudocode:

for 1, 2, and 3
   select A, B, or C
       then select from the numbers from 1, 2, 3 that were not selected
           then select from the letters A, B, C not yet selected 
                select final unselected number 
                       select final unselected letter 

Ideally, I'd want to be able to input the following:

numbers <- c("1", "2", "3")
letters <- c("A", "B", "C") 

And the output would look like something this. These are only the first three lines. The pattern would be the same for the categories beginning with B and beginning with C.

A1: A1 B2 C3, A1 B3 C2, A1 C2 B3, A1 C3 B2
A2: A2 B1 C3, A2 B3 C1, A2 C1 B3, A2 C3 B1
A3: A3 B1 C2, A3 B2 C1, A3 C1 B2, A3 C2 B1

Upvotes: 1

Views: 143

Answers (1)

Ivalbert Pereira
Ivalbert Pereira

Reputation: 304

If I understood correctly, you want a permutation with some exclusions.

The package "gtools" provide permutations function.

library(gtools)
v <- c("A1","A2","A3","B1","B2","B3","C1","C2","C3")
# Create the input dataframe
b <- data.frame(permutations(length(v),3,v))
# Create a new column with desired lines marked with "1"
b <- within(b, x4 <- {
  ifelse(
    (substr(X1,1,1) != substr(X2,1,1)) &
    (substr(X1,1,1) != substr(X3,1,1)) &
    (substr(X1,2,2) != substr(X2,2,2)) &
    (substr(X1,2,2) != substr(X3,2,2)) &
    (substr(X2,1,1) != substr(X3,1,1)) &
    (substr(X2,2,2) != substr(X3,2,2))
    ,1,0)  
})
# Exclude undesired lines marked with "0"
b <- b[b$x4 == 1,1:3]

Upvotes: 1

Related Questions