我有这个载体:
Vec=c("a" , "b", "c ", "d")
我希望这是数据框:
[,1] [,2] [,3] [,4]
[1,] a b c d
[2,] a b c d
[3,] a b c d
[4,] a b c d
[5,] a b c d
答案 0 :(得分:3)
使用rbind
和do.call
的一种方法是:
do.call(rbind, replicate(5, Vec, simplify = FALSE))
[,1] [,2] [,3] [,4]
[1,] "a" "b" "c " "d"
[2,] "a" "b" "c " "d"
[3,] "a" "b" "c " "d"
[4,] "a" "b" "c " "d"
[5,] "a" "b" "c " "d"
您可以将5
替换为您喜欢的任何号码。
replicate
在列表中返回Vec 5次(simplify = FALSE
创建列表)。这些元素使用rbind
do.call
编辑。
<强>更新强>
实际上使用matrix
可能是最好的:
> matrix(Vec, nrow=5, ncol=length(Vec), byrow=TRUE)
[,1] [,2] [,3] [,4]
[1,] "a" "b" "c " "d"
[2,] "a" "b" "c " "d"
[3,] "a" "b" "c " "d"
[4,] "a" "b" "c " "d"
[5,] "a" "b" "c " "d"
将nrow
参数更改为您想要的任何数字,然后就可以了。
所有3个答案都需要使用as.data.frame
转换为data.frame,因此我将其排除在微基准测试之外:
<强>微基准强>
> microbenchmark::microbenchmark(t(replicate(5, Vec)),
+ do.call(rbind, replicate(5, Vec, simplify = FALSE)),
+ matrix(Vec, nrow=5, ncol=4, byrow=TRUE),
+ times=1000)
Unit: microseconds
expr min lq mean median uq max neval
t(replicate(5, Vec)) 52.854 59.013 68.393740 63.374 70.815 1749.326 1000
do.call(rbind, replicate(5, Vec, simplify = FALSE)) 18.986 23.092 27.325856 25.144 27.710 105.708 1000
matrix(Vec, nrow = 5, ncol = 4, byrow = TRUE) 1.539 2.566 3.474166 3.079 3.593 29.763 1000
正如您所见,matrix
解决方案是迄今为止最好的解决方案。
答案 1 :(得分:3)
另一种选择:
t(replicate(5, Vec))
# [,1] [,2] [,3] [,4]
#[1,] "a" "b" "c " "d"
#[2,] "a" "b" "c " "d"
#[3,] "a" "b" "c " "d"
#[4,] "a" "b" "c " "d"
#[5,] "a" "b" "c " "d"