Replicate vector in R

I have a say vector vec = c(1,1), and I want to replicate its (cbind) column 10 times so that I can get something similar to matrix(1, 10, 2). Is there a function working on vecthat can perform this replication? i.e. rep (vec, 10)?

Thank!

+5
source share
3 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 guidelines:

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
+8
source

One of the options:

vec <- c(1,1)
t(replicate(10, vec))

> t(replicate(10, vec))
      [,1] [,2]
 [1,]    1    1
 [2,]    1    1
 [3,]    1    1
 [4,]    1    1
 [5,]    1    1
 [6,]    1    1
 [7,]    1    1
 [8,]    1    1
 [9,]    1    1
[10,]    1    1
+5
source

What about:

R> vec = c(1,2)
R> matrix(rep(vec, each=10), ncol=2)
     [,1] [,2]
 [1,]    1    2
 [2,]    1    2
 [3,]    1    2
 [4,]    1    2
 ....
+2
source

All Articles