R:所有可能的唯一结果的二进制矩阵 [英] R:Binary matrix for all possible unique results

查看:21
本文介绍了R:所有可能的唯一结果的二进制矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成所有可能的二进制矩阵'i' 变量 X 的排列,其中i"可以是任何介于 1 和无限之间的数字.结果矩阵将有 2^i 个唯一行.

How to generate a binary matrix for all possible permutations of 'i' variables X, where " i " can be any number between 1 and infinite. Resultant matrix will have 2^ i unique rows.

对于 i=2 ,变量 x1, x2 每个都有可能的值 1 或 0,所以得到的矩阵是:

For i=2 , variables x1, x2 each with a possible value of 1 or 0, so the resultant matrix would be:

X1 X2
0 0
0 1
1 0
1 1

R中有什么函数可以生成吗?

Is there any function in R to generate ?

我尝试了以下功能:

   matrix(rbinom(160, 1, 0.5),ncol=5,nrow=(2^5))

但结果并未显示所有可能的值.

But the result does not show all possible values.

推荐答案

你可以使用expand.grid:

 expand.grid(c(0,1),c(0,1))
  Var1 Var2
1    0    0
2    1    0
3    0    1
4    1    1

更一般地,以 5 列为例,给出 m:

More generally, with 5 columns for example, giving m:

m <- as.data.frame(matrix(rbinom(5*2, 1, 0.5),ncol=5))
 V1 V2 V3 V4 V5
1  0  1  1  0  0
2  0  1  1  0  0

dim(expand.grid(m))
32 5

这篇关于R:所有可能的唯一结果的二进制矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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