所有长度的无序组合 [英] Unordered combinations of all lengths
本文介绍了所有长度的无序组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一个函数,该函数可以将向量的所有无序组合返回给我.例如
I am looking a function that return me all the unordered combination of a vector. eg
x <- c('red','blue','black')
uncomb(x)
[1]'red'
[2]'blue'
[3]'black'
[4]'red','blue'
[5]'blue','black'
[6]'red','black'
[7]'red','blue','black'
我猜想某些库中有一个函数可以执行此操作,但是找不到.我正在尝试使用gtool
的permutations
,但这不是我想要的功能.
I guess that there is a function in some library that do this, but in can't find it. I am trying with permutations
of gtool
but it is not the function i am looking for.
推荐答案
您可以在combn()
函数的m
参数上应用长度为x
的序列.
You could apply a sequence the length of x
over the m
argument of the combn()
function.
x <- c("red", "blue", "black")
do.call(c, lapply(seq_along(x), combn, x = x, simplify = FALSE))
# [[1]]
# [1] "red"
#
# [[2]]
# [1] "blue"
#
# [[3]]
# [1] "black"
#
# [[4]]
# [1] "red" "blue"
#
# [[5]]
# [1] "red" "black"
#
# [[6]]
# [1] "blue" "black"
#
# [[7]]
# [1] "red" "blue" "black"
如果您喜欢矩阵结果,则可以将stringi::stri_list2matrix()
应用于上面的列表.
If you prefer a matrix result, then you can apply stringi::stri_list2matrix()
to the list above.
stringi::stri_list2matrix(
do.call(c, lapply(seq_along(x), combn, x = x, simplify = FALSE)),
byrow = TRUE
)
# [,1] [,2] [,3]
# [1,] "red" NA NA
# [2,] "blue" NA NA
# [3,] "black" NA NA
# [4,] "red" "blue" NA
# [5,] "red" "black" NA
# [6,] "blue" "black" NA
# [7,] "red" "blue" "black"
这篇关于所有长度的无序组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文