[R] Expanding rows of a data frame into multiple rows
Peter Meilstrup
peter.meilstrup at gmail.com
Sun Oct 23 01:51:24 CEST 2011
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?
More information about the R-help
mailing list