user4016111
user4016111

Reputation: 37

create a dataframe with random numbers

i am new to R. i want a data frame of 8 columns with random numbers like:-

V1  V2   V3..... V8
 1  101  1        1
 2  102  0        1
 3  103  0        1
 .   .   .        .
 .   .   .        .
 .   .   .        .
 .   .   .        .
100 200  1        0

V3-V8 are columns containing sequence of 1 and 0 only.

Upvotes: 1

Views: 4955

Answers (3)

PAC
PAC

Reputation: 5366

That's easy :

  • Choose the number of observation N = 100
  • Sample in a standard normal using rnorm
  • Sample a number between 1 and 10 using sample
  • Sample a character with sample
  • Sample in a uniform distribution using runif and generate a binary variable using 1*(runif(N) < p)

Here is the code :

N  <- 100
df  <- data.frame(id = 1:N, x1 = rnorm(N), x2 = sample(1:10, size = N, replace = TRUE), x3 = sample(letters[1:10], size = N, replace = TRUE), x4 = 1*(runif(n = N) < .75))

Upvotes: 1

akrun
akrun

Reputation: 886938

Another variation of @David Arenburg's solution

 as.data.frame(cbind(matrix(seq_len(n*n1), ncol=n1),
      matrix(sample(0:1, n*reps, replace=TRUE), ncol=reps)))

where,

 n <- 100; reps <- 6; n1 <- 2

n is the number of rows, reps is the number of columns with random numbers, n1 is the number of initial columns

Upvotes: 2

David Arenburg
David Arenburg

Reputation: 92282

Try

n <- 100 ; m <- 200 ; reps <- 6 
as.data.frame(cbind(matrix(seq_len(m), n, m/n), 
                    replicate(reps, sample(c(0, 1), n, replace = TRUE))))
#      V1  V2 V3 V4 V5 V6 V7 V8
# 1     1 101  0  1  1  0  0  0
# 2     2 102  1  1  1  0  0  1
# 3     3 103  0  0  0  1  1  1
# 4     4 104  1  1  0  1  1  0
# ...

Where n is number of rows. m is the number you want to seq_len in your first columns. reps is the number of columns you want to add with random numbers between 0 and 1

Upvotes: 3

Related Questions