首页 > 解决方案 > 在 r 中使用 cast、spread 或 melt 重塑数据表

问题描述

我有一个关于重塑表格的问题

这是我的表:

Dispatch_Table:

Name    Year    Month   Day Hour Value
 AA     2020       1     1   1   100
 AA     2020       1     1   2   200
 BB     2020       1     1   1   300
 BB     2020       1     1   2   400
 CC     2020       1     1   1   500
 CC     2020       1     1   2   600
 DD     2020       1     1   1   700
 DD     2020       1     1   2   800

所需的表应该如下所示:

`Year    Month   Day     Hour      AA     BB      CC      DD    
  2020     1       1       1      100     300     500     700   
  2020     1       1       2      200     400     600     800`

我尝试了cast,mestspread函数,但没有任何效果。每次都走错方向。我不明白如何在castmelt函数中选择 ID 和变量。这些是我的尝试:

Reshaped_table<- reshape(Dispatch_Table, idvar = "Name", timevar c("Year","Month","Day","Hour"), direction = "wide")

reshaped<-melt(Dispatch_Table, id=c("Year"),direction = "wide")

reshaped<-dcast(Dispatch_Table, Name ~ ID, value.var ="value" )

reshaped<-spread(Dispatch_Table,Year,Month,Day,Hour)

我没有得到任何改进的解决方案。任何帮助将不胜感激。谢谢你。

标签: rreshape

解决方案


推荐阅读