我有一个向量说vec = c(1,1)
,我想要将它(cbind)列复制10次,这样我就能得到类似matrix(1, 10, 2)
的东西。是否有一个可以vec
运行的函数可以执行此复制?即rep(vec,10)?
谢谢!
答案 0 :(得分:8)
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
或@Joshua指出:
tcrossprod(rep(1,10),vec)
一些基准:
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
答案 1 :(得分:5)
一个选项是:
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
答案 2 :(得分:2)
怎么样:
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
....