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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With