【问题标题】:Why reshape2's Melt cannot capture rownames in the transformation?为什么 reshape2 的 Melt 无法捕获转换中的行名?
【发布时间】:2013-11-18 13:27:31
【问题描述】:

我有以下数据:

Cubn    3.71455160837536    0.237454645363458
Gm9779  2.56051657980096    0.20850752817264
Apod    3.51796703048962    0.195999214485821

我想要做的是创建“融化”的数据,以便它给出这个

       var1 var2     value
1      FOO Cubn   3.7145516
2      FOO Gm9779 2.5605166
3      FOO Apod   3.5179670
4      BAR Cubn   0.2374546
5      BAR Gm9779 0.2085075
6      BAR Apod   0.1959992

但是为什么失败了?

 library("reshape2");
 dat <-read.table("http://dpaste.com/1446132/plain/",header=FALSE)
 rownames(dat) <- dat[,1]
 dat[,1] <- NULL
 colnames(dat) <- c("FOO","BAR");
 head(dat)
 longData <- melt(dat);
 head(longData)

【问题讨论】:

    标签: r reshape reshape2


    【解决方案1】:

    我不知道 为什么 部分,但我知道您可以通过 meltmatrix 而不是 data.frame 来获取行名:

    melt(as.matrix(dat))
    #     Var1 Var2     value
    # 1   Cubn  FOO 3.7145516
    # 2 Gm9779  FOO 2.5605166
    # 3   Apod  FOO 3.5179670
    # 4   Cubn  BAR 0.2374546
    # 5 Gm9779  BAR 0.2085075
    # 6   Apod  BAR 0.1959992
    

    您必须查看melt 函数的代码才能知道它为什么会这样。特别是,reshape2:::melt.matrix 的代码具有以下几行,它们将在上面的示例中创建前两列:

    labels <- expand.grid(lapply(dn, var.convert), KEEP.OUT.ATTRS = FALSE, 
        stringsAsFactors = FALSE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 2020-06-12
      • 2015-06-08
      • 2016-07-27
      • 2013-05-04
      • 2014-03-17
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多