所有长度的无序组合

编程入门 行业动态 更新时间:2024-10-14 18:14:15
本文介绍了所有长度的无序组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一个函数,该函数可以将向量的所有无序组合返回给我.例如

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"

更多推荐

所有长度的无序组合

本文发布于:2023-11-29 20:09:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647502.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   长度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!