R 有效地添加时间序列中缺少的值

R 有效地添加时间序列中缺少的值,r,time-series,missing-data,R,Time Series,Missing Data,我有500个数据集(面板数据)。在每一种情况下,我都有一个跨越不同商店(商店)的时间序列(周)。在每个商店中,我需要添加缺失的时间序列观测值 我的数据示例如下: store week value 1 1 50 1 3 52 1 4 10 2 1 4 2 4 84 2

我有500个数据集(面板数据)。在每一种情况下,我都有一个跨越不同商店(商店)的时间序列(周)。在每个商店中,我需要添加缺失的时间序列观测值

我的数据示例如下:

store   week           value
1           1          50
1           3          52
1           4          10
2           1          4
2           4          84
2           5          2
我希望它看起来像:

store   week        value
1           1       50
1           2       0
1           3       52
1           4       10
2           1       4
2           2       0
2           3       0
2           4       84
2           5       2
我目前使用的代码如下(虽然有效,但需要花费很长时间处理数据):


存储这里有一个dplyr/tidyr选项,您可以尝试:

library(dplyr); library(tidyr)
group_by(df, store) %>% 
  complete(week = full_seq(week, 1L), fill = list(value = 0)) 
#Source: local data frame [9 x 3]
#
#  store  week value
#  (int) (int) (dbl)
#1     1     1    50
#2     1     2     0
#3     1     3    52
#4     1     4    10
#5     2     1     4
#6     2     2     0
#7     2     3     0
#8     2     4    84
#9     2     5     2
默认情况下,如果未指定
fill
参数,新行将填充
NA
。由于您似乎还有许多其他列,我建议您省去fill参数,这样您就可以使用NAs,如果需要,请使用
mutate\u each
执行另一个步骤,将NAs转换为0(如果合适的话)


谢谢我有比“值”更多的变量。那么我该如何调整代码的最后一部分呢?
library(dplyr); library(tidyr)
group_by(df, store) %>% 
  complete(week = full_seq(week, 1L), fill = list(value = 0)) 
#Source: local data frame [9 x 3]
#
#  store  week value
#  (int) (int) (dbl)
#1     1     1    50
#2     1     2     0
#3     1     3    52
#4     1     4    10
#5     2     1     4
#6     2     2     0
#7     2     3     0
#8     2     4    84
#9     2     5     2
group_by(df, store) %>% 
  complete(week = full_seq(week, 1L)) %>%
  mutate_each(funs(replace(., which(is.na(.)), 0)), -store, -week)