首页 文章

R - 计算滚动财务余额

提问于
浏览
0

我在R中创建了一个财务报告结构 . 我缺少的是数据框需要注入的最后一部分,我称之为“滚动 balancer ” .

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

Question: 如何将结果注入单元格,使用上方和左侧的单元格输入以计算结果 .

这是我的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

这就是“滚动 balancer ”的计算应该如何表现:

[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]

1 回答

  • 2

    人们会将此称为累积而不是滚动至少,因为它通常与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
    

相关问题