[R] Expanding rows of a data frame into multiple rows
Tyler Rinker
tyler_rinker at hotmail.com
Sun Oct 23 02:44:16 CEST 2011
To further Weidong Gu's suggestion merge would give you what you want but not the numeric column corresponding to the sector. Adding that would be easy enough via transform if you really desired it.
Tyler
obs.l<-sapply(input$observations,length)
desire.output<-data.frame(site=rep(1:6,obs.l),obs=unlist(input$observations))
merge(input[,-3], desire.output, all.x=TRUE)
----------------------------------------
> Date: Sat, 22 Oct 2011 20:34:04 -0400
> From: anopheles123 at gmail.com
> To: peter.meilstrup at gmail.com
> CC: r-help at r-project.org; manipulatr at googlegroups.com
> Subject: Re: [R] Expanding rows of a data frame into multiple rows
>
> This may work
>
> obs.l<-sapply(input$observations,length)
>
> desire.output<-data.frame(site=rep(1:6,obs.l),obs=unlist(input$observations))
>
> Weidong Gu
>
> On Sat, Oct 22, 2011 at 7:51 PM, Peter Meilstrup
> <peter.meilstrup at gmail.com> wrote:
> > The setup: I have a data frame where one column is in list mode, and
> > each entry contains a vector of varying length.
> > I want to expand this into a data frame with one row for each member
> > of the list-mode column (the other values being replicated)
> >
> > For example, an example input and the desired output would be:
> >
> > input <- data.frame(site = 1:6,
> > sector = factor(c("north", "south", "east",
> > "west", "east", "south")),
> > observations =
> > I(list(c(1,2,3),c(4,3),c(),c(14,12,53,2,4),c(3),c(23))))
> >
> > desired.output <-
> > data.frame(site = c(1,1,1,2,2,4,4,4,4,5,6),
> > sector = factor(c(2,2,2,3,3,4,4,4,4,4,1,3),
> > labels = c("east", "north", "south", "west")),
> > observations = c(1,2,3,4,3,14,12,53,2,4,3,23))
> >
> > There seems like there ought to be a good (simple, fast) way to do
> > this, but I've been struggling. Any ideas?
> >
> > ______________________________________________
> > 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.
> >
>
> ______________________________________________
> 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