Cbind vector several times in R

I have a vector that I would like to repeat n times, using the vector as columns in the new matrix

i have a vector

vec <- c(266, 130, 86, 69, 56, 39, 30, 44, 33, 43)
vec
[1] 266 130  86  69  56  39  30  44  33  43

I would like to produce n times

vec1 vec1
266  266
130  130
86   86
69   69
56   56
39   39
30   30
44   44  
33   33
43   43  .....

I am not completely familiar with do.call, but would you use this function to achieve this?

+4
source share
2 answers

R processes the vectors when creating the matrix, so you can:

matrix(vec , length(vec) , n )

where nis the number of columns / repetitions.

+11
source

Another obvious alternative here is to use replicate(although it matrixshould be more efficient):

> vec <- scan()
1: 266 130  86  69  56  39  30  44  33  43
11: 
Read 10 items
> replicate(5, vec)
      [,1] [,2] [,3] [,4] [,5]
 [1,]  266  266  266  266  266
 [2,]  130  130  130  130  130
 [3,]   86   86   86   86   86
 [4,]   69   69   69   69   69
 [5,]   56   56   56   56   56
 [6,]   39   39   39   39   39
 [7,]   30   30   30   30   30
 [8,]   44   44   44   44   44
 [9,]   33   33   33   33   33
[10,]   43   43   43   43   43

Or you can use a more critical (but possibly faster) approach, for example:

`dim<-`(rep(vec, 5), c(length(vec), 5))
+2
source

All Articles