gpt4 book ai didi

r - 将融化的数据帧重新构建回原始数据的更简单方法

转载 作者:行者123 更新时间:2023-12-04 15:00:33 25 4
gpt4 key购买 nike

如何重新创建 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)
})

我错过了什么?这是显而易见的,但我想不出答案。我什至可能以前在这里为其他人回答过。啊。

最佳答案

如果您添加某种形式的标记来指示项目属于哪个原始行,那么很容易:

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)

您遇到的困难是无法确定哪些项目组合在一起。熔融组中的 1:5 排是一排吗?还是 2:6 和 1 放错了位置?融化的数据实际上是融化的:)

关于r - 将融化的数据帧重新构建回原始数据的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15867650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com