r - 固定利率衰减的累积存款
问题描述
我正在尝试模拟每年沉积的死木中生物量的积累。木材以每年 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 年每年存款的剩余生物量。
解决方案
欢迎来到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
推荐阅读
- c++ - C++ 数组队列实现方法错误
- excel - MS Excel,G Sheet,用 OR 逻辑计算多个条件
- android - Android PageKeyedDataSource(分页库)回调错误处理(src中有TODO异常)
- sql - Rails 结合了 group by 和 min
- javascript - 如何在ajax中引用文本字段名称?
- python - Matplotlib 未正确读取时间轴
- android - 我需要一个设置注册按钮的解决方案,检查第 7 行,注册活动在 Android Studio 上显示为红色
- tumblr - 如何摆脱 tumblr 上照片转发页面上的转发/点赞历史记录?
- solr - 返回 solr 中一个文档的扩展结果
- xml - 为 Dynamics 365 执行 XML xrmtoolbox 出现错误“字典中不存在给定的键”