[R] How to repeat vectors ?

Tong Wang wangtong at usc.edu
Sun Oct 1 06:35:58 CEST 2006


Hi, 
    Thanks you guys for all the help. I learned a lot from it.  
    It looks using apply() is not an efficient way, since all it does is looping through 
each row(or col) , which would be slow for large matrix, right ? 

cheers

----- Original Message -----
From: Gabor Grothendieck <ggrothendieck at gmail.com>
Date: Saturday, September 30, 2006 4:54 am
Subject: Re: [R] How to repeat vectors ?
To: Tong Wang <wangtong at usc.edu>
Cc: r-help at stat.math.ethz.ch

> Here are 4 approaches in order from most compact
> to least.  #1 only works for numeric matrices, # 2 is
> a shorter versio of your solution using rep.vec and # 3
> is from Alex's post and is likely what I would
> use in practice.
> 
> m <- matrix(1:4, 2) # test matrix
> 
> # 1 - m must be numeric for this one to work
> kronecker(m, rep(1,2))
> 
> # 2
> apply(m, 2, rep, each = 2) # 2
> 
> # 3 - from Alex's post
> m[rep(1:nrow(m), each = 2),]
> 
> # 4
> matrix(rbind(c(m), c(m)), nc = ncol(m))
> 
> On 9/30/06, Tong Wang <wangtong at usc.edu> 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