r语言 - 在键首次出现后为当前没有数据的日期创建 0



我有一个表,看起来像下面的

33

我们可以在分组后使用complete:

library(lubridate) # formatting date
library(dplyr)
df %>% 
mutate(Date = as.Date(ydm(Date))) %>%  # you don't need this if your date is in correct format
group_by(Key) %>% 
complete(Date = seq(min(Date), max(Date), by = "1 day"),
fill = list(Metric = 0))
Key   Date       Metric
<chr> <date>      <dbl>
1 A     2021-01-01      6
2 A     2021-01-02      3
3 A     2021-01-03      0
4 A     2021-01-04      0
5 A     2021-01-05      3
6 B     2021-01-03      4
7 B     2021-01-04      1
8 B     2021-01-05      2

我打赌有更短的方法,但这应该可以工作:

library(tidyverse)
df %>%
# get min and max date within Key
group_by(Key) %>%
mutate(minDate = min(Date), maxDate = max(Date)) %>%
ungroup() %>%
# make row for every Key / Date combo
complete(Key, Date, fill = list(Metric = 0)) %>%
# only keep the ones in that Key's range
filter(Date >= minDate, Date <= maxDate)

相关内容

  • 没有找到相关文章

最新更新