Simpler way to reconstitute a melted data frame ba

2019-01-27 23:15发布

问题:

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.

回答1:

If you add some form of marker to indicate which original row an item belongs to, then it is easy:

require(reshape2)
iris$rn <- seq_len(nrow(iris))
molten  <- melt(iris, id.vars = c("Species", "rn"))

# just a one-liner
dcast(molten, rn + Species ~ variable)

The difficulty you are encountering is that there is no way to identify which items go together. Are the 1:5 rows in the molten set one row? or is it the 2:6 and the 1 is misplaced? Melted data is in fact, melted :)



标签: r reshape2