如何生成向量的所有可能组合 [英] How can I generate all the possible combinations of a vector
本文介绍了如何生成向量的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个向量,比如 A,B,C,D,E
,我有兴趣生成向量元素的所有可能组合.下面给出了所需的输出.
I have a vector, say A,B,C,D,E
and I am interested in generating all the possible combination of the vector elements. The desired output is given below.
BA
,CA
,DA
,EA
,CB
,DB
、EB
、DC
、EC
、ED
推荐答案
尝试
combn(v1, 2, FUN=function(x) paste(rev(x), collapse="-"))
#[1] "B-A" "C-A" "D-A" "E-A" "C-B" "D-B" "E-B" "D-C" "E-C" "E-D"
如果你想按默认顺序
combn(v1, 2, FUN=paste, collapse="-")
#[1] "A-B" "A-C" "A-D" "A-E" "B-C" "B-D" "B-E" "C-D" "C-E" "D-E"
更新
为了更快的选择,您可以使用 grBase
中的 combnPrim
.检查此处
Update
For a faster option, you can use combnPrim
from grBase
. Check here
library(grBase)
apply(combnPrim(v1,2), 2, FUN=paste, collapse='-')
#[1] "A-B" "A-C" "B-C" "A-D" "B-D" "C-D" "A-E" "B-E" "C-E" "D-E"
数据
v1 <- LETTERS[1:5]
这篇关于如何生成向量的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文