在 dbplyr 中填写缺失值

Fill in missing values in dbplyr

我在数据库中的数据如下所示:

ID    month_year   value
1     01/06/2014   10
1     01/07/2014   100
1     01/10/2014   25

我要补缺的月份:

ID    month_year   value
1     01/06/2014   10
1     01/07/2014   100
1     01/08/2014   NA
1     01/09/2014   NA
1     01/10/2014   25

我正在使用 BigQuery 包来使用 dbplyr。我知道这在带有 UNNEST(GENERATE_DATE_ARRAY(... 的 BigQuery 中是可能的,但我无法使用 dbplyr。可能与 this github issue

有关

您可以使用外部联接来执行此操作。

list_of_dates = data_with_missing_dates %>%
  select(month_year) %>%
  distinct()

data_with_filled_dates = data_with_missing_dates %>%
  right_join(list_of_dates, by = "month_year")

这些都是标准的 dplyr 命令,因此 dbplyr 可以将它们转换为 bigquery。

以上假设您现有的数据包括您想要在最终输出中的所有日期(但分布在不同的 ID 值),因此 list_of_dates 可以从您的初始数据集构建。

如果初始数据中的任何 ID 都没有出现您希望在最终数据中出现的日期,那么您将需要以其他方式构建 list_of_dates。在这种情况下,即使 complete() 本身也不够。

编辑以便每个 ID 都有自己的开始和结束

list_of_dates = data_with_missing_dates %>%
  select(month_year) %>%
  distinct() %>%
  mutate(placeholder = 1)

date_limits = data_with_missing_dates %>%
  group_by(ID) %>%
  summarise(min_date = min(month_year),
            max_date = max(month_year)) %>%
  mutate(placeholder = 1)

data_with_filled_dates = date_limits %>%
  outer_join(list_of_dates, by = "placeholder") %>%
  filter(min_date <= month_year,
         max_date >= month_year) %>%
  select(ID, month_year) %>%
  left_join(data_with_missing_dates, by = c("ID", "month_year"))