将 NA 替换为上一行的值

replace NA with value of the previous row

我有一个像这样的数据框,有开始和结束月份和年份。

ID  start_month start_year  end_month   end_year
1   1   2018    5   2019
2   5   1981    NA  1999
2   7   1973    NA  1981
2   7   1963    NA  1973

我有几个月份的缺失数据,我希望能够用值替换它们并让日期相互跟随。 我想根据 ID.

将 NA 替换为 - 1 之前行的开始月份

对于日期 NA-1999,因为它是主题 2 中的最近日期并且之后没有日期,我想为该月输入 7。

我想得到这样的东西:

ID  start_month start_year  end_month   end_year
1   1   2018    5   2019
2   5   1981    7   1999
2   7   1973    4   1981
2   7   1963    6   1973

我想到了使用这个:

df<-df %>% group_by(ID) %>% replace(end_month = ifelse(is.na(end_month), length(start_month)-1 , 7)) %>% ungroup()

我的“length(start_month)-1”参数和替换函数不起作用,我不知道还能做什么

很抱歉,如果这不是很清楚,书面解释起来很复杂...

提前感谢您的帮助

如果我没理解错的话,你想用以下规则替换同一个 ID 中的 end_month 中的 NAs:

  • start_month - 1 任何有较晚时期的时期
  • 每个 ID
  • 的最后一个时期 7

对吗?

如果是这样,那么这应该可以解决问题:

library(dplyr)

df %>% 
  group_by(ID) %>% 
  arrange(ID, desc(start_year), desc(start_month)) %>% 
  mutate(
    end_month = ifelse(is.na(end_month), lag(start_month) - 1, end_month),
    end_month = ifelse(is.na(end_month), 7, end_month)
  ) %>% 
  ungroup()

#> # A tibble: 4 × 5
#>      ID start_month start_year end_month end_year
#>   <dbl>       <dbl>      <dbl>     <dbl>    <dbl>
#> 1     1           1       2018         5     2019
#> 2     2           5       1981         7     1999
#> 3     2           7       1973         4     1981
#> 4     2           7       1963         6     1973

reprex package (v2.0.1)

于 2022-03-30 创建

数据

df <- tibble::tribble(
~ID,  ~start_month, ~start_year,  ~end_month,   ~end_year,
1,   1,   2018,    5,   2019,
2,   5,   1981,    NA,  1999,
2,   7,   1973,    NA,  1981,
2,   7,   1963,    NA,  1973
)

df
#> # A tibble: 4 × 5
#>      ID start_month start_year end_month end_year
#>   <dbl>       <dbl>      <dbl>     <dbl>    <dbl>
#> 1     1           1       2018         5     2019
#> 2     2           5       1981        NA     1999
#> 3     2           7       1973        NA     1981
#> 4     2           7       1963        NA     1973