[R] How to repeat vectors ?

Alex Brown alex at transitive.com
Sat Sep 30 13:15:59 CEST 2006


Solution:

m[rep(1:nrow(m),each=2),]

Explanation:

There is a simple and effective way to do this, using array slices.

for your input matrix, m:

 > m=matrix(paste("a",c(11,12,21,22),sep=""),2)
 > m
      [,1]  [,2]
[1,] "a11" "a21"
[2,] "a12" "a22"

you want to create

      [,1]  [,2]
[1,] "a11" "a21"
[2,] "a11" "a21"
[3,] "a12" "a22"
[3,] "a12" "a22"

First, let's just consider the simpler problem of vectors - taking  
the first column as an example:

 > v=m[,1]
 > v
[1] "a11" "a12"

and you want:

[1] "a11" "a11" "a12" "a12"

which is the first element, followed by another copy of the first,  
and then the second, followed by another copy of the second, ie:

 > v[c(1,1,2,2)]
[1] "a11" "a11" "a12" "a12"

can we generate the sequence c(1,1,2,2) automatically?  yes:

 > rep(c(1,2),each=2)
[1] 1 1 2 2

or:

 > rep(1:length(v),each=2)
[1] 1 1 2 2

So let's apply that to the vector:

 > v[rep(1:length(v),each=2)]
[1] "a11" "a11" "a12" "a12"

Going back to the matrix, we can see that we want to do the same  
thing, but to the rows of the matrix, instead of the elements of the  
vector:

Instead of length, we use nrow, and we use the row specifier [r,]

 > m[rep(1:nrow(m),each=2),]
      [,1]  [,2]
[1,] "a11" "a21"
[2,] "a11" "a21"
[3,] "a12" "a22"
[4,] "a12" "a22"


-Alex

On 30 Sep 2006, at 07:33, Tong Wang wrote:

> I just figured out a way to do this:
>           rep.vec <- function(X,n)    return(t(array(rep(X,n),c 
> (length(X),n))))
>
>    Then,    apply(MyMatrix, 2, rep.vec,2)
>
> Is there a better way ?  Is there an internal function to repeat a  
> vector or matrix ?
>
> Thanks a lot.
>
>
> ----- Original Message -----
> From: Tong Wang <wangtong at usc.edu>
> Date: Friday, September 29, 2006 11:23 pm
> Subject: How to repeat vectors ?
> To: r-help at stat.math.ethz.ch
>
>> Hi,
>>    If I have a matrix  , say       a11   a12
>>                                                   a21  a22
>>    Is there a routine to get:      a11  a12
>>                                                     a11  a12
>>                                                     a21   a22
>>                                                     a21   a22
>>
>>     Thanks a lot for any help.
>>
>> best
>>
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting- 
> guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list