Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler way to reconstitute a melted data frame back to the original

Tags:

r

reshape2

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.

like image 960
Maiasaura Avatar asked Apr 07 '13 20:04

Maiasaura


People also ask

What does R melt function do?

R melt() function. The melt() function in R programming is an in-built function. It enables us to reshape and elongate the data frames in a user-defined manner. It organizes the data values in a long data frame format.

What does melting data mean?

The melt() function is used to convert a data frame with several measurement columns into a data frame in this canonical format, which has one row for every observed (measured) value.

What library is melt in R?

The melt function is to be found in the reshape package. If you do not have that package installed, then you will need to install it with install. packages("reshape") before you can use it. Then, when the package is installed, make it available with library(reshape) .


1 Answers

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 :)

like image 77
Ricardo Saporta Avatar answered Sep 30 '22 17:09

Ricardo Saporta