在R中按一定顺序熔化datafarame

时间:2018-05-15 10:11:54

标签: r dataframe reshape melt

我正在尝试融化这个数据集:

raw1 <- c("Alpha", "2018-04-01", "566.0", "647.75", "669.08", "673.08", "675.00")
raw2 <- c("Alpha", "2018-04-02", "563.3", "651.08", "670.67", "684.58", "671.17")
mydf <- as.data.frame(rbind(raw1, raw2))
names(mydf) <-  c("name", "date", "h1", "h2", "h3", "h4", "h5")
mydf

  name       date    h1     h2     h3     h4     h5
Alpha 2018-04-01 566.0 647.75 669.08 673.08 675.00
Alpha 2018-04-02 563.3 651.08 670.67 684.58 671.17

使用:

mynewdf <- melt(mydf, id.vars = c("name","date"), variable.name = "hour", value.name = "desiredName", measure.vars = names(mydf[,3:7]))
mynewdf

我明白了:

    name       date hour desiredName
1  Alpha 2018-04-01   h1       566.0
2  Alpha 2018-04-02   h1       563.3
3  Alpha 2018-04-01   h2      647.75
4  Alpha 2018-04-02   h2      651.08
5  Alpha 2018-04-01   h3      669.08
6  Alpha 2018-04-02   h3      670.67
7  Alpha 2018-04-01   h4      673.08
8  Alpha 2018-04-02   h4      684.58
9  Alpha 2018-04-01   h5      675.00
10 Alpha 2018-04-02   h5      671.17

但我想得到:

      name       date hour desiredName
Alpha 2018-04-01   h1       566.0
Alpha 2018-04-01   h2      647.75
Alpha 2018-04-01   h3      669.08
Alpha 2018-04-01   h4      673.08
Alpha 2018-04-01   h5      675.00
Alpha 2018-04-02   h1       563.3
Alpha 2018-04-02   h2      651.08
Alpha 2018-04-02   h3      670.67
Alpha 2018-04-02   h4      684.58
Alpha 2018-04-02   h5      671.17

我试图按“小时”排列,但R不识别此变量中的任何顺序。我应该将其声明为订单的因素吗?有没有办法直接从熔化函数中以所需的方式排列?

感谢

1 个答案:

答案 0 :(得分:-1)

我不确定我是否理解你的问题。添加以下代码会导致所需的输出。

mynewdf %>% dplyr::arrange(date, hour)

enter image description here