我如何重新创建一个data.frame
我融化的reshape2
?
可重现的例子
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
我试过的dcast
dcast(df, Species~variable, value.var = "value")
# should work but doesn't
临时解决方案
# 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)
})
我错过了什么?这很明显,但我无法弄清楚答案。我什至可能以前在这里为其他人回答过。啊。