R中的n个bernoulli随机变量的置换 [英] Permutation of n bernoulli random variables in R

查看:49
本文介绍了R中的n个bernoulli随机变量的置换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组n个变量,每个变量可以取0或1的值.我想使用R来获取一个包含所有可能值的矩阵(或数据帧等). n个值的排列.例如,如果n = 3,则可能的值为:

I have a set of n variables, each of which can take a value of 0 or 1. I'd like to use R to get a matrix (or data frame etc it doesn't matter) that consists of all possible permutations of the n values. For example if n=3 the possible values are:

 111
 110
 101
 100
 010
 011
 001
 000

我如何在R中做到这一点?

How could I do this in R?

推荐答案

您可以使用expand.grid进行操作.

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

输出:

   #   Var1 Var2 Var3
   # 1    0    0    0
   # 2    1    0    0
   # 3    0    1    0
   # 4    1    1    0
   # 5    0    0    1
   # 6    1    0    1
   # 7    0    1    1
   # 8    1    1    1

如果要将其粘贴为一项,则可以选择:

If you want to paste it as one item then you may choose:

do.call("paste0", expand.grid(0:1,0:1,0:1))

这将导致:

[1] "000" "100" "010" "110" "001" "101" "011"
[8] "111"

还应@Jilber Urbina的建议,可以使用:expand.grid(1:0,1:0,1:0)[3:1]用于不同的顺序

Also as suggested by @Jilber Urbina , one may use: expand.grid(1:0,1:0,1:0)[3:1] for a different order

概括该解决方案:

一个人也可以做:expand.grid(rep(list(0:1), 3)),这里3是重复次数,因此有人可以根据需要将其更改为20或100.

one can also do: expand.grid(rep(list(0:1), 3)) , Here 3 is the no of repeats, so someone can change it to 20 or 100 basis their needs.

替代方法:

gtools::permutations(n=2,r=3, v=0:1, repeats.allowed = T)

这篇关于R中的n个bernoulli随机变量的置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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