Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicate vector in R

I have a vector say vec = c(1,1) and I want to replicate it (cbind) column wise 10 times so I can get something that looks like matrix(1, 10, 2). Is there a function that operates on vec that can do this replication? i.e. rep(vec, 10)?

Thanks!

like image 955
Michael Avatar asked Feb 13 '13 16:02

Michael


1 Answers

vec <- c(1,2)
rep(1,10) %*% t.default(vec)
      [,1] [,2]
 [1,]    1    2
 [2,]    1    2
 [3,]    1    2
 [4,]    1    2
 [5,]    1    2
 [6,]    1    2
 [7,]    1    2
 [8,]    1    2
 [9,]    1    2
[10,]    1    2

Or as @Joshua points out:

tcrossprod(rep(1,10),vec)

Some benchmarks:

library(microbenchmark)

microbenchmark(rep(1,10) %*% t.default(vec),
               matrix(rep(vec, each=10), ncol=2),
               t.default(replicate(10, vec)),
               tcrossprod(rep(1,10),vec),times=1e5)

Unit: microseconds
                                   expr    min     lq  median      uq       max
1 matrix(rep(vec, each = 10), ncol = 2)  2.819  3.699  4.3970  5.3700  2132.240
2         rep(1, 10) %*% t.default(vec)  2.456  3.185  3.6750  5.5370  2121.746
3         t.default(replicate(10, vec)) 57.741 62.987 64.3740 65.9590 26654.678
4           tcrossprod(rep(1, 10), vec)  2.192  2.924  3.3745  5.2465  2145.709
like image 200
Roland Avatar answered Nov 09 '22 22:11

Roland