[R] reshape a wide data frame from wide to a long format with metadata columns
hadley wickham
h.wickham at gmail.com
Mon May 19 19:19:51 CEST 2008
Hi Alan,
> I have a general question about reshaping a wide data frame using the
> "reshape" command. I have a data frame consisting of 108 columns that
> I would like to convert to a long table and remove the metadata
> (embedded in the column names of the wide table) to new metadata
> columns in the long format.
You could try using the reshape _package_ (http://had.co.nz/reshape) to do this:
data1 <- data.frame(
name = 0:10,
mediacont.21.MC1A = 10:20,
mediatreat.20.MD1A = 30:40,
treat.20.T2C = 50:60,
treat.20.T2A = 70:80,
condtp.20.C2A = 90:100,
condtp.20.C2B = 100:110,
mediacont.21.MC1B = 120:130
)
dm <- melt(data1, id = "name")
head(dm)
ids <- colsplit(dm$variable, "\\.", c("treatment","time","rep"))
dm <- cbind(dm, ids)
dm$variable <- NULL
dm$time <- as.numeric(dm$time)
It's then easy to reshape and aggregate as required:
cast(dm, treatment ~ time, mean)
cast(dm, ... ~ treatment)
Hadley
--
http://had.co.nz/
More information about the R-help
mailing list