[R] How to duplicate each row in a data.frame?

Phil Spector spector at stat.berkeley.edu
Fri Dec 4 21:17:50 CET 2009


df[rep(1:nrow(df),each=3),]

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at 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 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.
>




More information about the R-help mailing list