几个字母的所有可能排列,允许组合长度不同

时间:2019-02-19 09:40:18

标签: r

我想从字符列表中获取所有可能的排列。可能的排列包括2、3、4和5个字母的组合。

我的信是:

  

A,   R,   N,   T,   F,   G,   B

我主要看的是permute::allPermscombncombinat::permn。但是这些似乎都无法解决我正在研究的问题。

预期结果

列出2个字母,3个字母,4个字母,5个字母的组合的所有可能排列。字母的顺序无关紧要,因此ARRA可以相同,并且最好只包含其中一个。

AR, AN, AT, AF, AG, AB, RN, RT, RF, RG, RB, NT, NF, NG, NB, ..., ARN, ART, ARF, ..., FGB, ARNT, ARNF, ARNG, ARNB, ..., ARNTF, ARNTG, ARNTB, ...

1 个答案:

答案 0 :(得分:3)

您可以使用combn创建组合,并按如下所示创建每个组合中的paste元素:

l <- c("A", "R", "N", "T", "F", "G", "B")
unlist(lapply(2:5, function(n) combn(l, n, paste, collapse="")))

输出:

  [1] "AR"    "AN"    "AT"    "AF"    "AG"    "AB"    "RN"    "RT"    "RF"    "RG"    "RB"    "NT"    "NF"    "NG"    "NB"    "TF"    "TG"    "TB"    "FG"    "FB"   
 [21] "GB"    "ARN"   "ART"   "ARF"   "ARG"   "ARB"   "ANT"   "ANF"   "ANG"   "ANB"   "ATF"   "ATG"   "ATB"   "AFG"   "AFB"   "AGB"   "RNT"   "RNF"   "RNG"   "RNB"  
 [41] "RTF"   "RTG"   "RTB"   "RFG"   "RFB"   "RGB"   "NTF"   "NTG"   "NTB"   "NFG"   "NFB"   "NGB"   "TFG"   "TFB"   "TGB"   "FGB"   "ARNT"  "ARNF"  "ARNG"  "ARNB" 
 [61] "ARTF"  "ARTG"  "ARTB"  "ARFG"  "ARFB"  "ARGB"  "ANTF"  "ANTG"  "ANTB"  "ANFG"  "ANFB"  "ANGB"  "ATFG"  "ATFB"  "ATGB"  "AFGB"  "RNTF"  "RNTG"  "RNTB"  "RNFG" 
 [81] "RNFB"  "RNGB"  "RTFG"  "RTFB"  "RTGB"  "RFGB"  "NTFG"  "NTFB"  "NTGB"  "NFGB"  "TFGB"  "ARNTF" "ARNTG" "ARNTB" "ARNFG" "ARNFB" "ARNGB" "ARTFG" "ARTFB" "ARTGB"
[101] "ARFGB" "ANTFG" "ANTFB" "ANTGB" "ANFGB" "ATFGB" "RNTFG" "RNTFB" "RNTGB" "RNFGB" "RTFGB" "NTFGB"