Home > Net >  Fill a NA matrix using apply functions
Fill a NA matrix using apply functions

Time:08-21

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:)

CodePudding user response:

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

CodePudding user response:

You can use the following code with apply:

set.seed(1)
tmp <- matrix(NA, 10, 10)
apply(is.na(tmp), 2, function(x) tmp[, x] <- 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

Created on 2022-08-20 with reprex v2.0.2

  • Related