A,A,A,A,B,B,B,B,B的唯一组合的R问题号 [英] R Question Number of Unique Combinations of A,A,A,A,B,B,B,B,B

查看:55
本文介绍了A,A,A,A,B,B,B,B,B的唯一组合的R问题号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来在R中获得A,A,A,A,B,B,B,B,B的所有可能唯一排列的列表。

I am trying to find a way to get a list in R of all the possible unique permutations of A,A,A,A,B,B,B,B,B.

组合最初被认为是获得解决方案的方法,因此组合可以回答。

Combinations was what was originally thought to be the method for obtaining a solution, hence the combinations answers.

推荐答案

我认为这就是您所追求的。 @bill建议将 unique combn 结合起来。我们还将使用Apply系列生成所有组合。由于 unique 会删除重复的行,因此我们需要在 unique 之前转置 combn 中的结果。然后,我们将它们换位,然后返回屏幕,以便每一列代表一个唯一的答案。

I think this is what you're after. @bill was on the ball with the recommendation of combining unique and combn. We'll also use the apply family to generate ALL of the combinations. Since unique removes duplicate rows, we need to transpose the results from combn before uniqueing them. We then transpose them back before returning to the screen so that each column represents a unique answer.

#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" 

...

编辑由于该问题是关于置换而不是组合,因此上述答案不是有用的。 这篇文章概述了一个函数,用于生成给定的唯一排列一组参数。我不知道是否可以改进,但这是使用该功能的一种方法:

EDIT Since the question is about permuations and not combinations, the answer above is not that useful. This post outlines a function to generate the unique permutations given a set of parameters. I have no idea if it could be improved upon, but here's one approach using that function:

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)

这篇关于A,A,A,A,B,B,B,B,B的唯一组合的R问题号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆