tidyr :: gather vs reshape2 :: melt.data.frame

时间:2018-09-25 03:29:22

标签: r tidyr melt tidy

两个函数都可以做类似的事情。

但是,gather函数更为冗长,因为它要求我指定应转换为列值的列名称。有没有一种整洁的方法可以在melt.data.frame内指定id.vars(例如在gather中)?

例如,我经常获得如下所示的时间序列数据。每个月都会增加一个月的数据。我不想每次获得额外一个月的数据时都更改gather函数中的参数。

library(tibble)
library(dplyr)
library(reshape2)
library(tidyr)

df <- tribble(

  ~key1, ~key2, ~`01/01/2008`, ~`02/01/2008`,
  "a", "b", 2, 4,
  "c", "d", 1, 3,

)

df

### using reshape2::melt

df_melt <- melt(df, id.vars=c("key1", "key2"), variable.name="Date")

df_melt


### using gather

df_gather <- gather(df, Date, value, `01/01/2008`:`02/01/2008`)

df_gather

更新: 问题是重复的。答案是here

在我的示例中,

df_gather <- gather(df, Date, value, -key1, -key2)

0 个答案:

没有答案