R找到所有可能的独特组合

问题描述 投票:0回答:3

我正在尝试在 R 中找到所有可能的独特组合。似乎有很多类似的问题被问到,但我无法找到相同的问题。

我的问题是从向量 x 中找到 m 个元素的组合,但 m 可能大于 x。例如,从 letter[1:2] 中选取 3 个元素,希望可以返回:

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 出现错误 < m. There are similar functions including gtools:permutations, expand.grid.

如果之前有人问过同样的问题,但我没听清,再次道歉。谢谢。

r combinations combn
3个回答
7
投票

有一些专门为此构建的软件包。基本前提是我们需要重复长度为

m
的组合,其中
m
可能大于输入向量。我们从经典的
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 链接的包):

## library(arrangements)
arrangements::combinations(letters[1:2], 3, 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
的基础包之一提供,但是它的缺点之一是它不允许重复(这是这里所需要的)。我为与此完全相同的问题写了一篇全面的概述,可以在这里找到:A Walk Through a Slice of Combinatorics in R


1
投票
combn1=function(x,m){
  n=ifelse(length(x)==1,ifelse(is.numeric(x),x,1),length(x))
  if(n>=m) return(combn(x,m))
  a=do.call(expand.grid, rep(list(x),m))
  b=t(unique(t(apply(a,1,sort))))
  `dimnames<-`(b,NULL)
}

combn1(letters[1],3)
     [,1]
[1,] "a" 
[2,] "a" 
[3,] "a" 
> combn1(letters[1:2],3)
     [,1] [,2] [,3] [,4]
[1,] "a"  "a"  "a"  "b" 
[2,] "a"  "a"  "b"  "b" 
[3,] "a"  "b"  "b"  "b" 
> combn1(letters[1:3],3)
     [,1]
[1,] "a" 
[2,] "b" 
[3,] "c" 

1
投票

这也许有效,它列出了所有独特的组合而不重复

> v1 = letters[1:4]
> v1 
[1] "a" "b" "c" "d"

> do.call("c",lapply(seq_along(v1),function(i) utils::combn(v1,i,FUN=list)))


[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

[[4]]
[1] "d"

[[5]]
[1] "a" "b"

[[6]]
[1] "a" "c"

[[7]]
[1] "a" "d"

[[8]]
[1] "b" "c"

[[9]]
[1] "b" "d"

[[10]]
[1] "c" "d"

[[11]]
[1] "a" "b" "c"

[[12]]
[1] "a" "b" "d"

[[13]]
[1] "a" "c" "d"

[[14]]
[1] "b" "c" "d"

[[15]]
[1] "a" "b" "c" "d"

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.