Phil Spector's solution is the best way to get your triplicating job done. As for why the result of your apply call is a 6 by 4 matrix, read the help file for apply where it talks about how it 'simplifies' the result. For FUN's that do not return a scalar the simplification algorithm may be surprising if MARGIN!=2: it cbind's the vectors output by FUN together no matter what the value of MARGIN was.
R : > m<-matrix(12:1,byrow=TRUE,nrow=4) R : > m R : [,1] [,2] [,3] R : [1,] 12 11 10 R : [2,] 9 8 7 R : [3,] 6 5 4 R : [4,] 3 2 1 R : > apply(m,1,function(x)x+1000) R : [,1] [,2] [,3] [,4] R : [1,] 1012 1009 1006 1003 R : [2,] 1011 1008 1005 1002 R : [3,] 1010 1007 1004 1001 In addition, calling apply on a data.frame converts it to a matrix before doing anything and that often loses or alters information in the data.frame. You definitely will not get a data.frame out of apply. apply has its uses, but it is limited. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of Phil Spector > Sent: Friday, December 04, 2009 12:18 PM > To: Peng Yu > Cc: r-h...@stat.math.ethz.ch > Subject: Re: [R] How to duplicate each row in a data.frame? > > df[rep(1:nrow(df),each=3),] > > - Phil Spector > Statistical Computing Facility > Department of Statistics > UC Berkeley > spec...@stat.berkeley.edu > > > On Fri, 4 Dec 2009, Peng Yu wrote: > > > I want to duplicate each line in 'df' 3 times. But I'm confused why > > 'z' is a 6 by 4 matrix. Could somebody let me know what the correct > > way is to duplicate each row of a data.frame? > > > > df=expand.grid(x1=c('a','b'),x2=c('u','v')) > > n=3 > > z=apply(df,1 > > ,function(x){ > > result=do.call(rbind,rep(list(x),n)) > > result > > } > > ) > > z > > > > ______________________________________________ > > R-help@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. > > > > ______________________________________________ > R-help@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. > ______________________________________________ R-help@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.