r - R:每一步计算利息和余额
问题描述
我有一个愚蠢的问题,但我无法通过滞后/领先或其他事情轻松解决
假设我有这张表,我的初始余额为 100,位置是我是否出价,百分比是我出价时得到的,我如何计算余额以获得这样的东西?
Position Percentage_change Balance
0 0.01 100
0 - 0.01 100
1 0.02 102
1 0.05 107.1
0 - 0.02 107.1
1 0.03 110.3
解决方案
cumprod
是您正在寻找的功能,例如
df <- data.frame(Position = c(0,0,1,1,0,1),
Percentage_change = c(0.01, -0.01, 0.02, 0.05, -0.02, 0.03))
# convert in to multiplier form eg 100 * 1.01
df$Multiplier <- df$Percentage_change + 1
# when position is 0, reset this to 1 so there is no change to the balance
df[df$Position == 0, ]$Multiplier <- 1
# take starting balance of 100 and times by cumulative product of the multipliers
df$Balance <- 100 * cumprod(df$Multiplier)
df
Position Percentage_change Multiplier Balance
1 0 0.01 1.00 100.000
2 0 -0.01 1.00 100.000
3 1 0.02 1.02 102.000
4 1 0.05 1.05 107.100
5 0 -0.02 1.00 107.100
6 1 0.03 1.03 110.313
推荐阅读
- node.js - Firebase 堆栈“错误:实体的索引条目过多”
- android - 将凌空响应添加到全局变量
- excel - 如何在 excel 嵌套 AND 公式中显示哪些 AND 条件失败
- python - Neo4j 导入 csv 并在一列中拆分值
- python - 为什么代码的结果是-5,而不是-4?
- c++ - 如何避免分段错误
- ajax - 自定义模板不起作用/页面空白显示“members-grid.php”(最终成员插件)Wordpress
- vue.js - html的动态渲染不起作用vue js
- python - 两列之间的字符串匹配
- python - 如何将基于 pytorch cpu 的转换转换为基于 cuda 的转换?