Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...