在R中转置时间序列数据

时间:2018-06-10 14:42:09

标签: r dataframe dplyr reshape

here my dataset
df=structure(list(id = c(1030879980L, 1030879990L), jan = c(170L, 
265L), feb = c(153L, 332L), march = c(170L, 290L), apr = c(1L, 
425L), may = c(66L, 406L), jume = c(125L, 352L), jul = c(129L, 
339L), aug = c(-109L, 470L), sept = c(56L, 486L), oct = c(37L, 
440L), nov = c(52L, 589L), dec = c(63L, 659L)), .Names = c("id", 
"jan", "feb", "march", "apr", "may", "jume", "jul", "aug", "sept", 
"oct", "nov", "dec"), class = "data.frame", row.names = c(NA, 
-2L))

如何将其垂直移调以进行时间序列分析。 有很多障碍。我无法手动完成。 在我预期的输出

id          month      value
1030879980  jan         507
1030879981  feb         502
1030879982  march       431
1030879983  apr 429
1030879984  may 449
1030879985  jume    368
1030879986  jul 406
1030879987  aug 290
1030879988  sept    309
1030879989  oct 371
1030879990  nov 481
1030879991  dec 536
1030879990  jan 265
1030879991  feb 332
1030879992  march   290
1030879993  apr 425
1030879994  may 406
1030879995  jume    352
1030879996  jul 339
1030879997  aug 470
1030879998  sept    486
1030879999  oct 440
1030880000  nov 589
1030880001  dec 659

如何执行?

1 个答案:

答案 0 :(得分:1)

您可以使用meltdata.table个套件中的reshape2功能:

library(data.table)
dt <- data.table(df)
dt.ts <- melt(dt, id.vars = "id", value.name = "value")