Hi there, I have a question on manipulating a matrix. Say I have a matrix A with 3 rows. I want to generate a new matrix B with 3 duplicates of the first row of A, 2 duplicates of the second row, and 4 duplicates of the third row. So B is a matrix with 9 rows. Or more general, I want to generate (3, 2, 4, 5) duplicates of rows 1-4 of a matrix with 4 rows. Is there a simple function to do it? Thanks a lot! Lei
Hi Lei, one way to do this is the following: mat <- matrix(rnorm(4*6), 4, 6) ind <- c(3, 2, 4, 5) mat[rep(seq_along(ind), ind), ] I hope it helps. Best, Dimitris Lei Liu wrote:> Hi there, > > I have a question on manipulating a matrix. Say I have a matrix A with 3 > rows. I want to generate a new matrix B with 3 duplicates of the first > row of A, 2 duplicates of the second row, and 4 duplicates of the third > row. So B is a matrix with 9 rows. Or more general, I want to generate > (3, 2, 4, 5) duplicates of rows 1-4 of a matrix with 4 rows. Is there a > simple function to do it? Thanks a lot! > > Lei > > ______________________________________________ > R-help at r-project.org 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. >-- Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus University Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014
How about this:> mat <- matrix(rep(1:4, each=4), nrow=4, byrow=TRUE) > mat[rep(1:4, times=c(3,2,4,5)),]Cheers, Simon. On Wed, 2009-06-17 at 01:54 -0400, Lei Liu wrote:> Hi there, > > I have a question on manipulating a matrix. Say I have a matrix A > with 3 rows. I want to generate a new matrix B with 3 duplicates of > the first row of A, 2 duplicates of the second row, and 4 duplicates > of the third row. So B is a matrix with 9 rows. Or more general, I > want to generate (3, 2, 4, 5) duplicates of rows 1-4 of a matrix with > 4 rows. Is there a simple function to do it? Thanks a lot! > > Lei > > ______________________________________________ > R-help at r-project.org 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.-- Simon Blomberg, BSc (Hons), PhD, MAppStat. Lecturer and Consultant Statistician School of Biological Sciences The University of Queensland St. Lucia Queensland 4072 Australia Room 320 Goddard Building (8) T: +61 7 3365 2506 http://www.uq.edu.au/~uqsblomb email: S.Blomberg1_at_uq.edu.au Policies: 1. I will NOT analyse your data for you. 2. Your deadline is your problem. The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data. - John Tukey.