更新时间:2023-02-10 18:32:11
为此专门构建了一些软件包.基本前提是我们需要重复长度为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.