我试图找到一种方法来获得A,A,A,A,B,B,B,B,B的所有可能的唯一排列的R列表。
组合是最初被认为是获得解决方案的方法,因此组合答案。
答案 0 :(得分:3)
我认为这就是你所追求的。 @bill提出了将unique
和combn
结合起来的建议。我们还将使用apply family来生成所有组合。由于unique
删除了重复的行,因此我们需要在combn
之前调整unique
的结果。然后我们将它们转换回来,然后返回到屏幕,以便每列代表一个独特的答案。
#Daters
x <- c(rep("A", 4), rep("B",5))
#Generates a list with ALL of the combinations
zz <- sapply(seq_along(x), function(y) combn(x,y))
#Filter out all the duplicates
sapply(zz, function(z) t(unique(t(z))))
返回:
[[1]]
[,1] [,2]
[1,] "A" "B"
[[2]]
[,1] [,2] [,3]
[1,] "A" "A" "B"
[2,] "A" "B" "B"
[[3]]
[,1] [,2] [,3] [,4]
[1,] "A" "A" "A" "B"
[2,] "A" "A" "B" "B"
[3,] "A" "B" "B" "B"
...
编辑由于问题是关于permeations而不是组合,上面的答案并没有那么有用。 This post概述了在给定一组参数的情况下生成唯一排列的函数。我不知道它是否可以改进,但这是使用该功能的一种方法:
fn_perm_list <-
function (n, r, v = 1:n)
{
if (r == 1)
matrix(v, n, 1)
else if (n == 1)
matrix(v, 1, r)
else {
X <- NULL
for (i in 1:n) X <- rbind(X, cbind(v[i], fn_perm_list(n -
1, r - 1, v[-i])))
X
}
}
zz <- fn_perm_list(9, 9)
#Turn into character matrix. This currently does not generalize well, but gets the job done
zz <- ifelse(zz <= 4, "A", "B")
#Returns 126 rows as indicated in comments
unique(zz)
答案 1 :(得分:2)
无需生成排列,然后挑选出独特的排列。 这是一种更简单的方法(并且更快,也更快):为了生成4 A和5 B的所有排列,我们只需要列举在9个可能位置中放置4 A的所有可能方式。这只是一个组合问题。以下是我们如何做到这一点:
x <- rep('B',9) # vector of 9 B's
a_pos <- combn(9,4) # all possible ways to place 4 A's among 9 positions
perms <- apply(a_pos, 2, function(p) replace(x,p,'A')) # all desired permutations
9x126矩阵perms
的每一列都是唯一的排列4 A和5 B:
> dim(perms)
[1] 9 126
> perms[,1:4] ## look at first few columns
[,1] [,2] [,3] [,4]
[1,] "A" "A" "A" "A"
[2,] "A" "A" "A" "A"
[3,] "A" "A" "A" "A"
[4,] "A" "B" "B" "B"
[5,] "B" "A" "B" "B"
[6,] "B" "B" "A" "B"
[7,] "B" "B" "B" "A"
[8,] "B" "B" "B" "B"
[9,] "B" "B" "B" "B"