首页 > 解决方案 > 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

标签: r

解决方案


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

推荐阅读