填充缺少的月份以进行填充

时间:2019-02-25 08:25:10

标签: r dplyr

我使用的数据样本与下面的结构类似:

  ID Date           Score
  1  10.02.2012     5
  1  10.05.2012     5
  2  01.09.2016     8
  2  10.10.2016     8
  3  08.02.2015     3
  3  02.04.2015     3

我希望以某种方式将ist转换为以下形式:

  ID     Date        Score
  1      02.2012     5
  1      03.2012     5
  1      04.2012     5
  1      05.2012     5
  2      09.2016     8
  2      10.2016     8
  3      02.2015     3
  3      03.2015     3
  3      04.2015     3 

首先,我通过执行以下操作将字符日期转换为日期格式:

df$Date <- as.Date(df$Date,format="%d.%m.%Y")
df %>% group_by(ID) %>% complete(seq.Date(min(Date), max(Date), by="months"))

不幸的是,这对我不起作用。任何解决问题的想法将不胜感激!

要复制此案,请使用以下数据:

    df <- structure(list(ID = c(1, 1, 2, 2, 3, 3), Date = structure(c(15380, 
15470, 17045, 17084, 16474, 16527), class = "Date"), Score = c(5, 
5, 8, 5, 3, 3)), row.names = c(NA, -6L), class = "data.frame")

3 个答案:

答案 0 :(得分:1)

您的dput()与您的示例不同。

您可以使用as.yearmon()中的zoo来设置格式,并使用na.locf()来填补缺失。

library(dplyr)
library(zoo)

df %>% 
  group_by(ID) %>% 
  complete(Date = seq.Date(min(Date), max(Date), by = "months")) %>% 
  ungroup() %>% 
  mutate(Date = as.yearmon(Date)) %>% 
  mutate(Score = na.locf(Score, na.rm=T),
         type = na.locf(type, na.rm=T))
# # A tibble: 9 x 4
# ID Date          type  Score
# <dbl> <S3: yearmon> <chr> <dbl>
# 1     1 feb 2012      a         5
# 2     1 mar 2012      a         5
# 3     1 apr 2012      a         5
# 4     1 mag 2012      b         5
# 5     2 set 2016      a         8
# 6     2 ott 2016      a         8
# 7     2 nov 2016      a         8
# 8     2 dic 2016      a         8
# 9     3 feb 2015      a         3

答案 1 :(得分:1)

您可以使用tidyr的{​​{1}}。

fill

什么导致了哟:

library(tidyverse)

df %>%  
  group_by(ID) %>% 
  complete(Date = seq.Date(min(Date), max(Date + 10), by="months")) %>% 
  ungroup() %>% 
  fill(Score) %>% 
  mutate(Date = gsub("-", ".", format(as.Date(Date), "%m-%Y")))

答案 2 :(得分:0)

您可以尝试

library(tidyverse)
df %>% 
  select(ID, Date, Score) %>% 
  mutate(month = lubridate::month(Date)) %>% 
  group_by(ID) %>% 
  complete(month = full_seq(month,1), Score)