The easiest way to recreate a melted block of data back to the original

How do I create data.framethat 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 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? This is something obvious, but I can not understand the answer. Perhaps I even answered that for someone else here. Argh.

+5
source share
1 answer

If you add some form of marker to indicate which source line the element belongs to, then this 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 facing is that there is no way to determine which elements come together. Are rows 1: 5 in a molten set one row? or is it 2: 6, but 1 is inappropriate? The molten data actually melted :)

+6
source

All Articles