2017-03-16 153 views
0

上下文中,我正在寻找将一个宽时间序列数据帧融入长数据帧。这样我可以在ggplot2中绘制数据并构建一个堆积区域图。时间序列是不正规(缺少一些周末和节假日)如何将宽时间序列数据帧转换为长数据帧?

目前的数据帧貌似

df 
    date  item_1 item_2  item_3 ... 
1 1992-03-23  8.63  7.609  1.6546 ... 
2 1992-03-24  7.98  7.634  1.6533 ... 
... 

如何使用下面的代码转换成上述数据帧分成

date  variable value 
1 1992-03-23 item_1  8.63 
2 1992-03-23 item_2  7.609 
3 1992-03-23 item_3  1.6546 
2 1992-03-24 item_1  7.98 

我得到错误

> melted_df = melt(df) 
Using as id variables 
Error in as.Date.numer(value): 'origin' must be supplied 
+1

可能重复[重新生成data.frame从宽格式到长格式](http://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format) –

回答

1

你必须指定id.vars熔体函数第二个参数,它的工作原理:

require(reshape) 
df <- data.frame(date = as.Date(c("1992-03-23", "1992-03-24")), 
       item_1 = c(8.63, 7.98), 
       item_2 = c(7.609, 7.634), 
       item_3 = c(1.6546, 1.6533)) 

melt(df, "date") 

您将获得:

 date variable value 
1 1992-03-23 item_1 8.6300 
2 1992-03-24 item_1 7.9800 
3 1992-03-23 item_2 7.6090 
4 1992-03-24 item_2 7.6340 
5 1992-03-23 item_3 1.6546 
6 1992-03-24 item_3 1.6533 

希望这有助于

+0

这工作。我需要在公式中指定“日期”。 – LascieL

+0

如何指定一个子集?例如new_data_frame(其中:变量== item_1或变量== item_2) – LascieL

+0

我会用'require(dplyr)'做这个,然后: 'df_new < - melt(df,“date”)%>%filter(variable ==“item_1”| variable ==“item_2”)' – Codutie

0

或用gather

library(tidyverse) 

df <- data.frame(date = as.Date(c("1992-03-23", "1992-03-24")), 
       item_1 = c(8.63, 7.98), 
       item_2 = c(7.609, 7.634), 
       item_3 = c(1.6546, 1.6533)) 

df %>% gather(variable, value, -date) 

给人,

 date variable value 
1 1992-03-23 item_1 8.6300 
2 1992-03-24 item_1 7.9800 
3 1992-03-23 item_2 7.6090 
4 1992-03-24 item_2 7.6340 
5 1992-03-23 item_3 1.6546 
6 1992-03-24 item_3 1.6533 
相关问题