【问题标题】:R - Calculate rolling financial balanceR - 计算滚动财务余额
【发布时间】:2018-12-09 14:53:38
【问题描述】:

我正在 R 中创建一个财务报告结构。我缺少的是最后一部分,即数据框需要注入我称之为“滚动余额”的地方。

我主要想用基础 R 来解决这个问题,避免添加另一个 R 包。如果可能,计算应该使用矢量化计算而不是循环。

问题:如何将结果注入单元格,使用上方和左侧的单元格作为输入来计算结果。

这是我的 R 脚本:

############
# Create df1
############
'date'        <- '2018-10-01'
'product'     <- 0 
'bought'      <- 0
'sold'        <- 0
'profit.loss' <- 0
'comission'   <- 0
'result'      <- 0
'balance'     <- 0

df1 <- data.frame(
  date,
  product,
  bought,
  sold,
  profit.loss,
  comission,
  result,
  balance
    , stringsAsFactors=FALSE)

# Inject initial deposit
df1[1,8] <- 1000

##########################
# Create df2 (copying df1)
##########################
df2 <- df1

# Clean 
df2 <- df2[-c(1), ]     # Removing row 1.
df2[nrow(df2)+3,] <- NA # Create 3 rows.
df2[is.na(df2)] <- 0    # Change NA to zero.

# Populate the dataframe
df2$date      <- c('2018-01-01', '2018-01-02', '2018-01-03')
df2$product   <- c('prod-1', 'prod-2', 'prod-3')
df2$bought    <- c(100, 200, 300)
df2$sold      <- c(210, 160, 300)
df2$comission <- c(10, 10, 10)

# Merge both dataframes
df3 <- rbind(df1, df2)

#######
# Calcs
#######
df3$profit.loss <- df3$sold - df3$bought # calc profit.loss.
df3$result <- df3$profit.loss - df3$comission # calc result.

# [Xxx]# Balance <- Note! This is the specific calc connected to my question.


enter code here

运行R脚本后的结果:

        date product bought sold profit.loss comission result balance
1 2018-10-01       0      0    0           0         0      0    1000
2 2018-01-01  prod-1    100  210         110        10    100       0
3 2018-01-02  prod-2    200  160         -40        10    -50       0
4 2018-01-03  prod-3    300  300           0        10    -10       0

这就是“滚动余额”的计算方式:

   [Result] [Balance]

row-1: [No value]  [initial capital: 1000]
row-2: [100] [900 / Take value of balance, one row above, subscract left result]   
row-3: [-50] [850 / Take value of balance, one row above, subscract left result]
row-4: [follows the same principal as row-2 and row-3]

【问题讨论】:

  • @G. Grothendieck:根据您的输入,我尝试了以下行:df3$balance
  • @G. Grothendieck:似乎 df3[1,8] 中的初始资本值在 cumsum 运行时被覆盖,这可能是正常的,因为它将结果添加到列 df3[,8] 中。我试图将初始大写移动到列结果 df3[1,7] 然后它可以工作,因为 cumsum 然后将计算结果添加到 df3[1,8] 中。
  • @G.格洛腾迪克:随意总结一个答案,我会批准它,包括我们评论聊天的结果。
  • 已将我的 cmets 转移到一个答案中。

标签: r


【解决方案1】:

人们会将此称为累积而不是滚动,至少它通常与 R 一起使用。

如果初始余额是标量b 并且结果在向量result 中,那么b + cumsum(result) 是一个长度与result 相同的向量,它给出了初始余额加上结果的累积和。

b <- 10
result <- c(0, -1, 3)
b + cumsum(result)
## [1] 10  9 12

# same
c(b + result[1], b + result[1] + result[2], b + result[1] + result[2] + result[3])
## [1] 10  9 12

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2017-04-01
    • 2015-11-06
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多