R-计算滚动财务余额

时间:2018-12-09 14:53:39

标签: r

我正在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]

1 个答案:

答案 0 :(得分: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
相关问题