本文介绍了Tidyr :: gather vs.reshape2 ::在矩阵上融化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以一种非标准的方式长期使用reshape2::melt:我正在运行数值实验并得到一个矩阵.然后,我融化并生成一些图像.

I've been a long time user of reshape2::melt in a rather non-standard way: I'm running numeric experiments and get a matrix as a result. I then melt it and produce some images.

reshape2tidyr之间的相似性的启发,我现在正在尝试在类矩阵的对象上实现相同的输出.到目前为止没有运气:

Inspired by the similarity between reshape2 and tidyr, I'm now trying to achieve identical output on objects of class matrix. No luck so far:

library(reshape2)
library(tidyr)

set.seed(42)
mat <- matrix(runif(6), 3)
mat2 <- mat
colnames(mat2) <- letters[1:2]
rownames(mat2) <- letters[3:5]

melt(mat)
melt(mat2)
gather(mat) # fails
gather(mat2) # fails

请注意,melt很聪明,如果存在dimnames,则保留它们.我已经了解了它是如何工作的,因此我可以将以下功能添加到方法分派中:

Note that melt is smart and keeps dimnames if they are present. I've learnt how it works, so I can potentially add the following function to the method dispatch:

gather.matrix <- function(mat) {
  if (is.null(dimnames(mat))) {
    grid <- expand.grid(seq.int(nrow(mat)), seq.int(ncol(mat)))
  } else {
    grid <- expand.grid(dimnames(mat))
  }
  cbind(grid, value = as.vector(mat))
}

all.equal(melt(mat), 
          gather.matrix(mat))
#[1] TRUE
all.equal(melt(mat2), 
          gather.matrix(mat2))
#[1] TRUE

但是问题是,在我的情况下,我是否可以强制gather以与melt相同的方式执行操作?是否有任何参数组合会在matmat2上产生所需的输出?

But the question is, can I force gather act in the same way as melt in my case? Is there any combination of parameters that would produce the desired output on mat and mat2?

推荐答案

也许会出现一个更好的答案,但是与此同时,我会将我的评论转换为答案:

Perhaps a better answer will emerge, but in the meantime, I'll convert my comments to an answer:

从README报价为"tidyr":

Quoting from the README to "tidyr":

...,然后从自述文件转到"dplyr":

... and from the README to "dplyr":

因此,一种是有意义的,因为它没有用于矩阵的方法.

As such, it sort of makes sense to not have methods for matrices.

由于gather已经包装了melt,因此如果您真的想要matrix方法,则可以节省编写自定义函数的时间,而只需执行以下操作:

Since gather already wraps around melt, if you really wanted a matrix method, you can save yourself writing a custom function and just do something like:

gather.matrix <- reshape2:::melt.matrix

这篇关于Tidyr :: gather vs.reshape2 ::在矩阵上融化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 20:48