【问题标题】:Showing all possible combinations of categories with restrictions in R在 R 中显示所有可能的具有限制的类别组合
【发布时间】:2020-06-17 00:55:02
【问题描述】:

我有以下 9 个类别,分别代表一个实验中的不同条件。实际上,我有 25 个不同的条件,但为了简单起见,我只显示了 9 个。

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

每个人将看到 3 个类别。他们将看到每个字母(A、B、C)一次,并将看到每个数字(1、2、3)一次。顺序很重要。

例如,如果他们首先随机看到 A1,那么他们看到的第二个类别可能是 B2、B3、C2 或 C3。如果他们看到第二类 C3,那么第三类唯一剩下的选项就是 B2。另一个例子:如果他们随机先看到 C2,然后他们可以看到 B1、B3、A1 或 A3。如果他们第二次看到 A1,他们必须第三次看到 B3。

我的目标是创建一种有效的方式来找到所有可能的方式来向参与者展示 3 个类别,同时遵守我制定的规则。我知道如何手动执行此操作,但我认为 R 中有更好的方法。我只是不知道从哪里开始。您对我如何开始进行设置有什么建议吗?

这是一些伪代码:

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 

理想情况下,我希望能够输入以下内容:

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

输出看起来像这样。这些只是前三行。以 B 开头和以 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

【问题讨论】:

  • @RonakShah 我添加了输入和前 3 行输出的样本

标签: r dplyr apply tidyverse


【解决方案1】:

如果我理解正确,您想要一个带有一些排除项的排列。

“gtools”包提供排列功能。

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]

【讨论】:

  • 当初始类别的数量是 25 个(来自 5x5 网格)而不是 9 个(来自上面显示的 3x3 网格)时,是否有一种简单的方法来概括这一点?
  • 尝试像这样排列输入向量 v
猜你喜欢
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
相关资源
最近更新 更多