[R] Duplicate rows of matrix

Christos Hatzis christos at nuverabio.com
Fri Mar 9 18:41:14 CET 2007


Try this:

a <- matrix(c(8, 4.2, 9.4, 1.1),2) 
b <- c(3,1)

a[rep(1:nrow(a), b), ] 

-Christos

Christos Hatzis, Ph.D.
Nuvera Biosciences, Inc.
400 West Cummings Park
Suite 5350
Woburn, MA 01801
Tel: 781-938-3830
www.nuverabio.com
 


> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Bruno C.
> Sent: Friday, March 09, 2007 12:17 PM
> To: r-help
> Subject: [R] Duplicate rows of matrix
> 
> Hello my problem is the following:
> 
> I have a matrix A and a vector B which contains as many rows as A.
> 
> I need to build a matrix C which contains B[i]-times the row 
> A[i,] and this for each line of A.
> 
> if for example A is
> 
>     [1]    [2]
> [1]  8      9.4
> [2]  4.2    1.1
> 
> and B is (3,1). Then C will be:
>     [1]    [2]
> [1]  8      9.4
> [2]  8      9.4
> [3]  8      9.4
> [4]  4.2    1.1
> 
> 
> I have some working code which go through all the lines of A 
> and for each line does a rbind(C, A[i,]) B[i]-times But this 
> is quite time consuming given that each rbind rebuild a new 
> matrix ... is there any faster way?
> I can think of some minor improvements like building a matrix 
> C of zeros, containing as many columns as A and as many 
> columns as the sum of elements of B ... and the filing it.
> 
> But I was more looking for some already implemented 
> function/package, is there any?
> 
> Thanx
> 
> 
> 
> ------------------------------------------------------
> Leggi GRATIS le tue mail con il telefonino i-modeT di Wind 
> http://i-mode.wind.it
> 
> ______________________________________________
> 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