Create a matrix of 35 rows and 15 columns with numbers from 1 to 4 sampled randomly

Viewed 42

I am trying to create a matrix of 35 rows and 15 columns with numbers from 1 to 4 sampled randomly.

Can you please help me create it just using the matrix and sample functions? I am a noob. Not sure if cbind can be used here.

This is where I am:

m1 <- matrix(data = 1:525,  nrow = 35 ,ncol = 15)
sample (m1, 1:4, replace = TRUE)

I couldn't find what I needed in the R ?help section.

1 Answers

You generate a vector by randomly sampling from 1 to 4 with replacement and then converting the resulting vector into a matrix.

matrix(sample(x = 1:4, size = 35*15, replace = TRUE), nrow = 35, ncol = 15)

This also gives you the option to use other sampling method, like drawing from a binomial distribution.

matrix(rbinom(n = 35*15, 3, 0.5)+1, nrow = 35, ncol = 15)

Although I am not sure when I would use this compared to the sample() solution above.

EDIT: as @jay.sf mentioned, use e.g. set.seed(13) before randomly sampling numbers in order to be able to reproduce your results.

Related