Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65880185/create-a-matrix-of-35-rows-and-15-columns-with-numbers-from-1-to-4-sampled-rando

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...