Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind the same vector multiple times?

Tags:

r

How can I bind the same vector o = c(1,2,3,4) multiple times to get a matrix like:

o = array(c(1,2,3,4,1,2,3,4,1,2,3,4), dim(c(4,3))
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
[4,]    4    4    4

In a nicer way than: o = cbind(o,o,o) and maybe more generalized (duplicate)? I need this to specify colors for elements in textplot.

like image 698
hendrik Avatar asked Dec 03 '12 23:12

hendrik


2 Answers

R recycles. It's very eco-friendly:

o=c(1,2,3,4) 
> matrix(o,nrow = 4,ncol = 4)
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3
[4,]    4    4    4    4
like image 84
joran Avatar answered Oct 17 '22 21:10

joran


You can use replicate

> o = c(1,2,3,4) 
> replicate(4, o)
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3
[4,]    4    4    4    4
like image 24
GSee Avatar answered Oct 17 '22 21:10

GSee