在多行中绑定相同的向量

时间:2015-10-15 22:20:53

标签: r

我有这个载体:

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

2 个答案:

答案 0 :(得分:3)

使用rbinddo.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"