首页 > 解决方案 > 固定利率衰减的累积存款

问题描述

我正在尝试模拟每年沉积的死木中生物量的积累。木材以每年 4.6% 的速度腐烂。

我的数据被格式化:

Cols: Treatment, Year, New.deposit Treatment (A, B, C...) Year (0:105) New.deposit (numeric)

在过去的几天里,我尝试了大致如下的功能组合,但最终得到了错误的组合 - 也许我让事情变得太难了:

#OBS! These code attempts are incorrect.
df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum(lag(New.deposit, n=1, default=0))*(1-0.046))

df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum((lag(Accumulated.deposits, n=1, default=0)*(1-0.046))) + new.deposit

My goal is to have one variable, Accumulated.biomass.yearY = deposit.year0 *  (1-0.046)^(Y) + deposit.year1 * (1-0.046)^(Y-1) + deposit.year2 * (1-0.046)^(Y-2)..... deposit.yearY * (1-0.046)^(Y-Y).

我想要一个矩阵,显示 X 年每年存款的剩余生物量。

标签: rdplyr

解决方案


欢迎来到stackoverflow。你可以试试这样的东西吗?我喜欢打破这些步骤,以便更容易看到发生了什么。如果我不完全理解,请发表评论,我会更新我的答案。您还可以在您的问题中使用此示例数据框,并向我们展示您希望看到的输出,以便我们继续跟进。

library(tidyverse)

df <-
  tibble(
    treatment = rep(LETTERS[1:2], 5),
    years = rep(0:4, each = 2),
    new_deposit = rep(1:5*10, each = 2)
  ) %>% 
  arrange(treatment, years, new_deposit)


df %>%
  arrange(treatment, years) %>%
  group_by(treatment) %>%
  mutate(
    prev_deposit = lag(new_deposit, default = 0),  
    running_sum = cumsum(prev_deposit),
    accumulated = running_sum * (1-0.046)^(years)
  ) %>% 
  ungroup()

#  treatment years new_deposit prev_deposit running_sum accumulated
#  <chr>     <int>       <dbl>        <dbl>       <dbl>       <dbl>
#  A             0          10            0           0        0   
#  A             1          20           10          10        9.54
#  A             2          30           20          30       27.3 
#  A             3          40           30          60       52.1 
#  A             4          50           40         100       82.8 

推荐阅读