在R中为每个组添加缺失的行

时间:2019-02-21 12:09:42

标签: r datetime data.table

数据集:

.as-console-wrapper { max-height: 100% !important; top: 0; }

我有一个像这样的数据框

original <- data.frame(
            type = c(1,1,1,1,2,2,2,2),
            day = as.POSIXct(c("01-01-2000 00:00:00",
                               "01-01-2000 00:01:00",
                               "01-01-2000 00:02:00",
                               "01-01-2000 00:04:00",
                               "01-01-2000 12:00:00",
                               "01-01-2000 12:01:00",
                               "01-01-2000 12:02:00",
                               "01-01-2000 12:04:00"), format="%m-%d-%Y %H:%M:%S"),
            value = c(4, 3, 1, 1, 3, 5, 6, 3))

我想在每种类型中用值= 0填充丢失的分钟级别数据

因此,预期输出为

  type                 day value
1    1 2000-01-01 00:00:00     4
2    1 2000-01-01 00:01:00     3
3    1 2000-01-01 00:02:00     1
4    1 2000-01-01 00:04:00     1
5    2 2000-01-01 12:00:00     3
6    2 2000-01-01 12:01:00     5
7    2 2000-01-01 12:02:00     6
8    2 2000-01-01 12:04:00     3

我可以使用 type day value 1 1 2000-01-01 00:00:00 4 2 1 2000-01-01 00:01:00 3 3 1 2000-01-01 00:02:00 1 4 1 2000-01-01 00:03:00 0 5 1 2000-01-01 00:04:00 1 6 2 2000-01-01 12:00:00 3 7 2 2000-01-01 12:01:00 5 8 2 2000-01-01 12:02:00 6 9 2 2000-01-01 12:03:00 0 10 2 2000-01-01 12:04:00 3 解决此问题,但是我正在寻找padr解决方案。每个类型的组都有可能吗?

1 个答案:

答案 0 :(得分:1)

使用data.table,我们可以在扩展原始数据集后进行联接

new <- setDT(original)[, .(day = seq(first(day), last(day), by = "1 min"), value = 0),
  by =  type]
new[original, value := i.value, on = .(type, day)][]
#    type                 day value
# 1:    1 2000-01-01 00:00:00     4
# 2:    1 2000-01-01 00:01:00     3
# 3:    1 2000-01-01 00:02:00     1
# 4:    1 2000-01-01 00:03:00     0
# 5:    1 2000-01-01 00:04:00     1
# 6:    2 2000-01-01 12:00:00     3
# 7:    2 2000-01-01 12:01:00     5
# 8:    2 2000-01-01 12:02:00     6
# 9:    2 2000-01-01 12:03:00     0
#10:    2 2000-01-01 12:04:00     3

或使用tidyverse

library(tidyverse)
original %>%
   group_by(type) %>% 
   complete(day = seq(first(day), last(day), by = "1 min"), fill = list(value = 0))