Al14
Al14

Reputation: 1814

bind the same vector in multiple rows

I have this vector:

Vec=c("a" , "b", "c ", "d")

I want this as data frame:

      [,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

Upvotes: 1

Views: 776

Answers (2)

LyzandeR
LyzandeR

Reputation: 37879

One way using rbind and do.call would be:

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" 

You can replace 5 with any number you like.

replicate returns the Vec 5 times in a list (simplify = FALSE creates the list) . These elements are rbind-ed using do.call.

Update:

Actually using matrix is probably the best:

> 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" 

Change the nrow argument to whatever number you want and you ll have it ready.

All 3 answers will need to use as.data.frame to convert to a data.frame so I am excluding this from the microbenchmark:

Microbenchmark

> 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

As you can see the matrix solution is by far the best.

Upvotes: 3

talat
talat

Reputation: 70266

Another option:

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" 

Upvotes: 3

Related Questions