我有一个数据框架,其中包含不同年份的年增长值和特定年份的值,我想用该值向后降低该值,并用该值向前增加该值。示例数据集如下
ex_df = structure(list(year = c(2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025),
growth = c(1152, -2051, 1074, 1200, 1036, 1593, 1007, 1701, 1642, -1800, 1607),
value = c(NA, NA, NA, NA, NA, NA, NA, 11278, NA, NA, NA),
new_value = c(5874, 7026, 4975, 6049, 7642, 8678, 10271, 11278, 12979, 14621, 12821)),
class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -11L))
我尝试的代码如下
ex_df %>%
arrange(year) |>
mutate(cum_yr_increase = cumsum(growth),
new_value_2 = cum_yr_increase + value[year == 2024])