在每列中创建一个包含随机数的数据框

时间:2023-01-22 22:56:25

I have this simulation of 1000 random numbers:

我有1000个随机数的模拟:

a <-sample(0:1, 1000, rep = TRUE)

What I want is a data frame of ten columns, where the values of each column are generated like a.

我想要的是一个十列的数据框,其中每列的值生成像一个。

For example:

例如:

id  Column 1    Column2 .........Column 10
 1   1                              1
 2   0                              1
 3   1            
     0
     0
     .
     .  
1000 1                              1 

2 个解决方案

#1


24  

You are looking for replicate:

您正在寻找复制品:

data.frame(replicate(10,sample(0:1,1000,rep=TRUE)))

These are the top few rows:

这些是前几行:

  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1  1  1  0  1  0  0  1  1  1   0
2  0  0  0  1  0  1  0  0  1   0
3  0  1  1  1  1  0  1  1  1   1
4  0  0  0  1  1  1  1  1  1   0
5  1  0  1  0  1  1  0  1  1   0
6  0  1  1  1  1  1  0  1  1   1

If you do the same command without wrapping it in data.frame(), you will have a matrix. Matrices are faster to work with, so you might want to investigate whether they are suitable for your problem.

如果您执行相同的命令而不将其包装在data.frame()中,您将拥有一个矩阵。矩阵使用起来更快,因此您可能需要调查它们是否适合您的问题。

#2


6  

Why not generate all the numbers at once and use a matrix to make your columns. Additionally you can use rbinom to quickly generate these types of numbers:

为什么不一次生成所有数字并使用矩阵来创建列。此外,您可以使用rbinom快速生成以下类型的数字:

matrix(rbinom(10*1000, 1, .5), ncol=10)

PS I don't do exactly what you asked for b/c you said you're new to R. I assume you may not know about this way of generating numbers.

PS我没有完全按照你的要求做b / c,你说你是R的新手。我假设你可能不知道这种产生数字的方式。

#1


24  

You are looking for replicate:

您正在寻找复制品:

data.frame(replicate(10,sample(0:1,1000,rep=TRUE)))

These are the top few rows:

这些是前几行:

  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1  1  1  0  1  0  0  1  1  1   0
2  0  0  0  1  0  1  0  0  1   0
3  0  1  1  1  1  0  1  1  1   1
4  0  0  0  1  1  1  1  1  1   0
5  1  0  1  0  1  1  0  1  1   0
6  0  1  1  1  1  1  0  1  1   1

If you do the same command without wrapping it in data.frame(), you will have a matrix. Matrices are faster to work with, so you might want to investigate whether they are suitable for your problem.

如果您执行相同的命令而不将其包装在data.frame()中,您将拥有一个矩阵。矩阵使用起来更快,因此您可能需要调查它们是否适合您的问题。

#2


6  

Why not generate all the numbers at once and use a matrix to make your columns. Additionally you can use rbinom to quickly generate these types of numbers:

为什么不一次生成所有数字并使用矩阵来创建列。此外,您可以使用rbinom快速生成以下类型的数字:

matrix(rbinom(10*1000, 1, .5), ncol=10)

PS I don't do exactly what you asked for b/c you said you're new to R. I assume you may not know about this way of generating numbers.

PS我没有完全按照你的要求做b / c,你说你是R的新手。我假设你可能不知道这种产生数字的方式。