使用基于前面行的多个条件和公式将列添加到数据框

Add column to data frame with multiple conditions and formulas based on earlier rows

所以我有数据争论问题。

这是我的示例数据。

year <- c(2019, 2019, 2020, 2020, 2021, 2021, 2021)
sn <- c("AB1001", "AB1002", "AB1001", "DC1001", "AB1002", "AB1001", "AB1003")
hours <- c(150, 173, 189, 102, 175, 215, 98)
delta_hours <- c(150, 173, 39, 102, NA, NA, NA)
df <- data.frame(year, sn, hours, delta_hours)

生成此数据框:

year     sn hours delta_hours
1 2019 AB1001   150         150
2 2019 AB1002   173         173
3 2020 AB1001   189          39
4 2020 DC1001   102         102
5 2021 AB1002   175          NA
6 2021 AB1001   215          NA
7 2021 AB1003    98          NA

我需要做的是 mutate/update 2021 年的 delta_hours 列。具体来说,对于唯一的 sn(前几年没有),我希望能够简单地复制小时列中的信息。对于前几年出现的那些 sn,我想用最近一年的小时数减去 2021 年的小时数。所以对于 sn AB1001,我想取 215 - 189 以获得 26。对于 sn AB1003,我想简单地复制 98。当然,对于 2021 年之前的任何一年,我只想保留这些信息。

我的最终数据框基本上应该是这样的:

year     sn hours delta_hours
1 2019 AB1001   150         150
2 2019 AB1002   173         173
3 2020 AB1001   189          39
4 2020 DC1001   102         102
5 2021 AB1002   175           2
6 2021 AB1001   215          26
7 2021 AB1003    98          98

我假设我需要使用 case_when,并且我可以这样做来获取前几年的数据以简单地复制过来,但我不知道如何正确地进行减法。

感谢帮助!谢谢!

library(dplyr)

df %>% 
  group_by(sn) %>% 
  mutate(
    delta_hours = if_else(year == 2021, hours - lag(hours), delta_hours),
    delta_hours = if_else(is.na(delta_hours), hours, delta_hours)
  )

# A tibble: 7 x 4
# Groups:   sn [4]
   year sn     hours delta_hours
  <dbl> <chr>  <dbl>       <dbl>
1  2019 AB1001   150         150
2  2019 AB1002   173         173
3  2020 AB1001   189          39
4  2020 DC1001   102         102
5  2021 AB1002   175           2
6  2021 AB1001   215          26
7  2021 AB1003    98          98