Hello! I have 2 vectors: x<-letters[1:5] y<-1:3 Is there a way - without loops - to create a data frame such that we repeat the whole "y" within each level of "x" so that it looks like this: a 1 a 2 a 3 b 1 b 2 b 3 c 1 c 2 c 3 etc? Thank you! -- Dimitri Liakhovitski Ninah Consulting www.ninah.com
Never mind - found it: expand.grid(y,x) On Tue, Nov 2, 2010 at 4:57 PM, Dimitri Liakhovitski <dimitri.liakhovitski at gmail.com> wrote:> Hello! > > I have 2 vectors: > > x<-letters[1:5] > y<-1:3 > > Is there a way - without loops - to create a data frame such that we > repeat the whole "y" within each level of "x" so that it looks like > this: > > a 1 > a 2 > a 3 > b 1 > b 2 > b 3 > c 1 > c 2 > c 3 > > etc? > > Thank you! > > -- > Dimitri Liakhovitski > Ninah Consulting > www.ninah.com >-- Dimitri Liakhovitski Ninah Consulting www.ninah.com
Dimitri Liakhovitski <dimitri.liakhovitski at gmail.com> [Tue, Nov 02, 2010 at 09:57:04PM CET]:> Hello! > > I have 2 vectors: > > x<-letters[1:5] > y<-1:3 > > Is there a way - without loops - to create a data frame such that we > repeat the whole "y" within each level of "x" so that it looks like > this: > > a 1 > a 2 > a 3 > b 1 > b 2 > b 3 > c 1 > c 2 > c 3 > > etc??expand.grid -- Johannes H?sing There is something fascinating about science. One gets such wholesale returns of conjecture mailto:johannes at huesing.name from such a trifling investment of fact. http://derwisch.wikidot.com (Mark Twain, "Life on the Mississippi")
On Nov 2, 2010, at 4:58 PM, Dimitri Liakhovitski wrote:> Never mind - found it: expand.grid(y,x)Yes, that is one way and is a way that was illustrated yesterday for a very similar question on r-help by (perhaps?) Grothendieck). Another way is: data.frame(lets = rep(letters[1:5], each=3), nums=rep(1:3, 5) ) There are at least two different ways that rep() can be invoked and each= is not the default. -- david.> > On Tue, Nov 2, 2010 at 4:57 PM, Dimitri Liakhovitski > <dimitri.liakhovitski at gmail.com> wrote: >> Hello! >> >> I have 2 vectors: >> >> x<-letters[1:5] >> y<-1:3 >> >> Is there a way - without loops - to create a data frame such that we >> repeat the whole "y" within each level of "x" so that it looks like >> this: >> >> a 1 >> a 2 >> a 3 >> b 1 >> b 2 >> b 3 >> c 1 >> c 2 >> c 3 >> >> etc? >> >> Thank you! >> >> -- >> Dimitri Liakhovitski >> Ninah Consulting >> www.ninah.com >> > > > > -- > Dimitri Liakhovitski > Ninah Consulting > www.ninah.com > > ______________________________________________ > 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.David Winsemius, MD West Hartford, CT