user124123
user124123

Reputation: 1683

cbind a vector multiple times in R

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

i.e 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 entirely familiar with do.call but would you use that function to achieve this ?

Upvotes: 9

Views: 5648

Answers (2)

David Heckmann
David Heckmann

Reputation: 2939

R recycles vectors when you create a matrix, so you can use:

matrix( vec , length(vec) , n )

where n is the number of columns/repetitions.

Upvotes: 16

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

Another obvious alternative here is to use replicate (though matrix should 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 could take a more cryptic (but possibly faster) approach like:

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

Upvotes: 3

Related Questions