Question
I find myself using reshape2::melt
to obtain a single "long" data.frame
from a hierarchical list
of data.frame
objects. However, the column names of the result has the list hierarchy levels labeled as "L1", "L2", etc. However, since those levels have meaning, I want to give those columns meaningful names instead. What's the best way to do this? Can it be done using the single call to melt
?
I am not wed to melt
or reshape2
, so I am open to other approaches or packages.
Current setup
Let's suppose we have a hierarchical list of data.frame
objects such as this:
library(reshape2)
x <- structure(list(cyl_6 = structure(list(gear_3 = structure(list( mpg = 1:2, qsec = 3:4), .Names = c("mpg", "qsec"), row.names = c(NA, -2L), class = "data.frame"), gear_4 = structure(list(mpg = 5:6, qsec = 7:8), .Names = c("mpg", "qsec"), row.names = c(NA, -2L), class = "data.frame")), .Names = c("gear_3", "gear_4")), cyl_8 = structure(list(gear_3 = structure(list(mpg = 9:10, qsec = 11:12), .Names = c("mpg", "qsec"), row.names = c(NA, -2L), class = "data.frame"), gear_4 = structure(list(mpg = 13:14, qsec = 15:16), .Names = c("mpg", "qsec"), row.names = c(NA, -2L), class = "data.frame")), .Names = c("gear_3", "gear_4" ))), .Names = c("cyl_6", "cyl_8"))
When I use melt(x)
, I get the column name of "L1" for the cylinder count and "L2" for the gear count. I would like the column to say "cylinders
" and "gears
", respectively, instead.
mx <- melt(x)
Here's the output of head(mx)
. I do not want it to just say "L1" and "L2":
1> head(mx)
variable value L2 L1
1 mpg 1 gear_3 cyl_6
2 mpg 2 gear_3 cyl_6
3 qsec 3 gear_3 cyl_6
4 qsec 4 gear_3 cyl_6
5 mpg 5 gear_4 cyl_6
6 mpg 6 gear_4 cyl_6
So, I resort to setting "L1" and "L2" manually:
names(mx)[3:4] <- c("gears", "cylinders")
Desired output
Here's the desired final column name setup. I would like to be able to achieve this without resetting the "names" of mx manually as a separate step.
1> head(mx)
variable value gears cylinders
1 mpg 1 gear_3 cyl_6
2 mpg 2 gear_3 cyl_6
3 qsec 3 gear_3 cyl_6
4 qsec 4 gear_3 cyl_6
5 mpg 5 gear_4 cyl_6
6 mpg 6 gear_4 cyl_6