Why reshape2's Melt cannot capture rownames in the transformation?

倖福魔咒の 提交于 2019-12-31 10:04:34

问题


I have the following data:

Cubn    3.71455160837536    0.237454645363458
Gm9779  2.56051657980096    0.20850752817264
Apod    3.51796703048962    0.195999214485821

What I want to do is to create the 'melted' data such that it gives this

       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

But why this failed?

 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)

回答1:


I don't know the why part, but I do know that you can get the row names by melting a matrix instead of a 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

You'll have to look at the code to the melt function to know why it behaves this way. In particular, the code for reshape2:::melt.matrix has the following lines which will create the first two columns in the example above:

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


来源:https://stackoverflow.com/questions/19826832/why-reshape2s-melt-cannot-capture-rownames-in-the-transformation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!