考虑日期范围,从长到宽格式创建R中的时间序列列

时间:2019-02-20 07:00:10

标签: r time-series reshape wide-column-store

首先,我已经成功地将数据从长格式转换为宽格式。 数据如下。

+======+==========+======+======+
| Name |   Date   | Val1 | Val2 |
+======+==========+======+======+
| A    | 1/1/2018 |    1 |    2 |
+------+----------+------+------+
| B    | 1/1/2018 |    2 |    3 |
+------+----------+------+------+
| C    | 1/1/2018 |    3 |    4 |
+------+----------+------+------+
| D    | 1/4/2018 |    4 |    5 |
+------+----------+------+------+
| A    | 1/4/2018 |    5 |    6 |
+------+----------+------+------+
| B    | 1/4/2018 |    6 |    7 |
+------+----------+------+------+
| C    | 1/4/2018 |    7 |    8 |
+------+----------+------+------+

要将上表从长格式转换为宽格式,我使用了以下代码行:

test_wide <- reshape(test_data, idvar = 'Name', timevar = 'Date', direction = "wide" )

以上代码的结果如下:

+======+===============+===============+===============+===============+
| Name | Val1.1/1/2018 | Val2.1/1/2018 | Val1.1/4/2018 | Val2.1/4/2018 |
+======+===============+===============+===============+===============+
| A    | 1             | 2             |             5 |             6 |
+------+---------------+---------------+---------------+---------------+
| B    | 2             | 3             |             6 |             7 |
+------+---------------+---------------+---------------+---------------+
| C    | 3             | 4             |             7 |             8 |
+------+---------------+---------------+---------------+---------------+
| D    | NA            | NA            |             4 |             5 |
+------+---------------+---------------+---------------+---------------+

我面临的问题是我需要R考虑日期格式的Date列。日期列的范围从1/1/20181/4/2018,因为日期1/2/20181/3/2018中没有值,我看不到任何列为Val1.1/2/2018,{{ 1}},Val2.1/3/2018Val3.1/2/2018

我想转换为宽格式,这样我就可以获得日期Val3.1/3/20181/2/2018的列,即使这些列仅包含NULL。

这样做的原因是我需要将数据用作时间序列。

编辑:

复制并粘贴的初始数据:

1/3/2018

转换后的数据副本并粘贴:

Name Date Val1 Val2
A 1/1/2018 1 2
B  1/1/2018 2 3
C 1/1/2018 3 4
D 1/4/2018 4 5
A 1/4/2018 5 6
B  1/4/2018 6 7
C 1/4/2018 7 8
", header=TRUE)

dput(test_data)结果:

Name,Val1.1/1/2018,Val2.1/1/2018,Val1.1/4/2018,Val2.1/4/2018
A,1,2,5,6
B,2,3,6,7
C,3,4,7,8
D,NA,NA,4,5

2 个答案:

答案 0 :(得分:2)

一个tidyverse选项

library(lubridate)
library(tidyverse)

df %>% 
  mutate(Date=mdy(Date)) %>% 
  #Or you can do as.Date(Date,'%m/%d/%Y') to avoid loading `lubridate`
  complete(Name, Date = seq(min(Date), max(Date), 1)) %>%
  gather(key, value, -Name, -Date) %>%
  unite(Date, key, Date, sep = ".") %>%
  spread(Date, value)

答案 1 :(得分:1)

library(dplyr)
library(tidyr) #complete
library(data.table) #dcast and setDT
df %>% mutate(Date=as.Date(Date,'%m/%d/%Y')) %>% 
       complete(Name, nesting(Date=full_seq(Date,1))) %>%
       setDT(.) %>% dcast(Name ~ Date, value.var=c('Val2','Val1'))