代码之家  ›  专栏  ›  技术社区  ›  Maiasaura

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

  •  6
  • Maiasaura  · 技术社区  · 13 年前

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

    我错过了什么?这是显而易见的,但我无法找出答案。我甚至可能以前为这里的其他人回答过这个问题。啊。

    1 回复  |  直到 13 年前
        1
  •  6
  •   Arun    13 年前

    如果你 添加某种形式的标记 要指示项目属于哪个原始行,则很容易:

    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错了?熔化的数据实际上是熔化的:)