How do I recreate a data.frame
that I melted with reshape2
?
Reproducible example
library(reshape2)
library(plyr)
data(iris)
df <- melt(iris, id.vars="Species")
head(df)
Species variable value
1 setosa Sepal.Length 5.1
2 setosa Sepal.Length 4.9
3 setosa Sepal.Length 4.7
4 setosa Sepal.Length 4.6
5 setosa Sepal.Length 5.0
6 setosa Sepal.Length 5.4
# Great, I'd like to get the original iris back
What I've tried with dcast
dcast(df, Species~variable, value.var = "value")
# should work but doesn't
temporary solution
# This works but clearly it shouldn't be this hard.
ddply(df, .(Species), function(x) {
Species <- unique(x$Species)
x$id <- 1:dim(x)[1]
x$Species <- NULL
dat <- unstack(x, value~variable)
dat$Species <- Species
return(dat)
})
What am I missing? It's something obvious but I cannot figure out the answer. I may have even answered it for someone else here before. argh.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…