简体   繁体   中英

Create a dataframe with random numbers in each column

I have this simulation of 1000 random numbers:

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 

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM