30

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 
zx8754
  • 52,746
  • 12
  • 114
  • 209
CreamStat
  • 2,155
  • 6
  • 27
  • 43

2 Answers2

56

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.

Frank
  • 66,179
  • 8
  • 96
  • 180
  • how to make a nrow a random number? I'm trying to substitute `1000` with `sample(10:100,1)` but it doesn't work. – jangorecki May 20 '15 at 09:32
  • 1
    @jangorecki The `data.frame` call must be removed for it to work, giving a list of uneven vectors. If you still want it in a single data.frame, I think your best bet is asking a new question. The workarounds I've found -- `cbind.na`, `rbind.fill`, `rbindlist(res,fill=TRUE)` -- are all circuitous. Here's a thread that may be of help: http://r.789695.n4.nabble.com/How-to-join-matrices-of-different-row-length-from-a-list-td3177212.html – Frank May 20 '15 at 13:28
  • BTW, the syntax is `data.frame(replicate(col,sample(range,row,rep=TRUE)))` – alvas Dec 07 '17 at 01:03
14

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.

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519