生成向量元素所有可能组合的列表 [英] Generate list of all possible combinations of elements of vector

查看:17
本文介绍了生成向量元素所有可能组合的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在长度为 14 的向量中生成 0 和 1 的所有可能组合.有没有一种简单的方法可以将该输出作为向量列表,甚至更好的是数据帧?

I am trying to generate all possible combinations of 0 and 1's in a vector of length 14. Is there an easy way of getting that output as a list of vectors, or even better, a dataframe?

为了更好地展示我在寻找什么,假设我只想要一个长度为 3 的向量.我希望能够生成以下内容:

To demonstrate better what I am looking for, let's suppose that I only want a vector of length 3. I would like to be able to generate the following:

 (1,1,1), (0,0,0), (1,1,0), (1,0,0), (1,0,1), (0,1,0), (0,1,1), (0,0,0)

推荐答案

您正在寻找 expand.grid.

expand.grid(0:1, 0:1, 0:1)

或者,对于长案例:

n <- 14
l <- rep(list(0:1), n)

expand.grid(l)

这篇关于生成向量元素所有可能组合的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆