Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fill a NA matrix using apply functions

I want to fill an empty matrix using the apply function.
For example, my purpose is to simplify the following code

tmp <- matrix(NA, 10, 10)
tmp[, 1] <- sample(1:500, 10)
tmp[, 2] <- sample(1:500, 10)
...
tmp[, 10] <- sample(1:500, 10)

Is it possible to make the code above just one line using the apply function? If it is not, recommendation of any kind of simpler code may be helpful for me:)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use replicate():

set.seed(1)
replicate(10, sample(1:500, 10))

#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#  [1,]  324  481  213   89  111  172  280  371  331    84
#  [2,]  167   85   37  428  404   25  160  499  465   359
#  [3,]  129  277  105  463  412  375   14  104  484    29
#  [4,]  418  362  217  289   20  248  130  326   13   141
#  [5,]  471  438  366  340   44  198   45  471  296   252
#  [6,]  299  494  485  419  377  378  402  255  217   406
#  [7,]  270  330  165  326  343   39   22  492  176   221
#  [8,]  466  263  290  330   70  435  206  497  345   412
#  [9,]  187  329  362   42  121  298  230  498  279   108
# [10,]  307   79  382  422   40  390  193  103  110   304
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading