R找到所有可能的独特组合 [英] R find all possible unique combinations
问题描述
我正在尝试在R中找到所有可能的唯一组合.似乎有很多类似的问题要问,但是我找不到相同的问题.
I am trying to find all possible unique combinations in R. It seems that there have been a lot of similar questions asked, but I was not able to find the same one.
我的问题是从向量x中找到m个元素的组合,但是m可能大于x.例如,从字母[1:2]中选择3个元素,希望它们可以返回:
My question is to find combinations of m number of elements from vector x, but m could be larger than x. For example, pick 3 elements from letters[1:2], which hopefully can return:
combn(letters[1:2],3)
[,1] [,2] [,3] [,4]
[1,] "a" "a" "a" "b"
[2,] "a" "a" "b" "b"
[3,] "a" "b" "b" "b"
但是,组合函数n<中的错误;米有类似的功能,包括gtools:permutations,expand.grid.
But instead error in combn function n < m. There are similar functions including gtools:permutations, expand.grid.
如果有人之前曾问过同样的问题,请再次道歉,但我没有抓住.谢谢.
Apologize again if someone asked the same questions previously, but I did not catch it. Thanks.
推荐答案
为此专门构建了一些软件包.基本前提是我们需要重复长度为m
的组合,其中m
可能大于输入向量.我们从经典的gtools
开始:
There are a few packages specifically built for this. The basic premise is that we need combinations with repetition of length m
where m
could be larger than the input vector. We start with the classic gtools
:
library(gtools)
combinations(2, 3, letters[1:2], repeats.allowed = TRUE)
[,1] [,2] [,3]
[1,] "a" "a" "a"
[2,] "a" "a" "b"
[3,] "a" "b" "b"
[4,] "b" "b" "b"
然后是arrangements
,它是iterpc
(在上面的注释中由@Gregor链接的程序包)的替代物:
And then there is arrangements
which is a replacement for iterpc
(the package linked by @Gregor in the comments above):
library(arrangements)
arrangements::combinations(2, 3, letters[1:2], replace = TRUE)
[,1] [,2] [,3]
[1,] "a" "a" "a"
[2,] "a" "a" "b"
[3,] "a" "b" "b"
[4,] "b" "b" "b"
最后是我写的RcppAlgos
:
library(RcppAlgos)
comboGeneral(letters[1:2], 3, TRUE)
[,1] [,2] [,3]
[1,] "a" "a" "a"
[2,] "a" "a" "b"
[3,] "a" "b" "b"
[4,] "b" "b" "b"
combn
是一个很棒的功能,它作为R
的基本软件包之一提供,但是其缺点之一是它不允许重复(这是此处所要求的).我写了一个非常全面的概述,概述了与此类似的问题,可以在这里找到:遍历R中的组合法学.
combn
is an awesome function that ships as one of the base packages with R
, however one of its shortcomings is that it doesn't allow repetition (which is what is required here). I wrote a pretty comprehensive overview for problems exactly like this one that can be found here: A Walk Through a Slice of Combinatorics in R.
这篇关于R找到所有可能的独特组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!