I found this method http://www.r-bloggers.com/a-quick-way-to-do-row-repeat-and-col-repeat-rep-row-rep-col/
rep.row <- function(x, n){
matrix(rep(x, each = n), nrow = n)
}
And it seemed sensible if the matrices are stored by column major, however, it seems like filling by rows is quicker
rep.row2 <-function(x,n){
matrix(rep(x, n), nrow = n, byrow = T)
}
microbenchmark::microbenchmark(rep.row(1:3, 1e6), rep.row2(1:3, 1e6))
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# rep.row(1:3, 1e+06) 87.82939 93.68947 102.78089 101.15577 107.8194 299.2344 100 b
# rep.row2(1:3, 1e+06) 36.19100 38.77103 49.65996 41.92792 53.1815 248.6452 100 a
Finally there's another way that's quicker to code, using row names, this solution is based on (the more complex) http://stackoverflow.com/a/11121463
rep.row3 <-function(x,n){
rbind(x)[rep(1, n), ]
}
If you don't care about the output row names this method seems to be only slightly slower than filling by row
microbenchmark::microbenchmark(rep.row(1:3, 1e6), rep.row2(1:3, 1e6), rep.row3(1:3, 1e6))
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# rep.row(1:3, 1e+06) 89.63324 98.29943 111.91460 106.35437 114.39797 328.0548 100 b
# rep.row2(1:3, 1e+06) 37.09797 40.27853 50.94678 44.63228 57.84233 258.4279 100 a
# rep.row3(1:3, 1e+06) 41.37416 45.61449 58.75495 58.29156 64.41045 279.7043 100 a