有人可以帮助我找到opening_bal
和closing_bal
。
我拥有当月发生的所有交易汇总(新交易/转移交易/退出交易等),并且我也有期末余额
最后一个月。使用此数据,我需要进行重新计算。
library(tidyverse)
library(lubridate)
# this is the data and closing balance detail I have
df <- data.frame(stringsAsFactors=FALSE,
placement_status_type = c("opening_bal", "New", "Transfer", "Reinstated",
"Suspended", "Exit", "closing_bal"),
sep2018 = c(NA, 97, -40, 164, -221, -170, NA),
oct2018 = c(NA, 96, -40, 173, -208, -208, NA),
nov2018 = c(NA, 101, -36, 162, -206, -158, NA),
dec2018 = c(NA, 76, -27, 146, -128, -143, NA),
jan2019 = c(NA, 117, -23, 139, -168, -167, NA),
feb2019 = c(NA, 124, -39, 135, -156, -158, NA),
mar2019 = c(NA, 70, -18, 103, -173, -115, NA)
)
mar2019_closing_bal <- 1000
# This is the output I am looking for
df_output <- data.frame(stringsAsFactors=FALSE,
placement_status_type = c("opening_bal", "New", "Transfer", "Reinstated",
"Suspended", "Exit", "closing_bal"),
sep2018 = c(1899, 97, -40, 164, -221, -170, 1729),
oct2018 = c(1729, 96, -40, 173, -208, -208, 1542),
nov2018 = c(1542, 101, -36, 162, -206, -158, 1405),
dec2018 = c(1405, 76, -27, 146, -128, -143, 1329),
jan2019 = c(1329, 117, -23, 139, -168, -167, 1227),
feb2019 = c(1227, 124, -39, 135, -156, -158, 1133),
mar2019 = c(1133, 70, -18, 103, -173, -115, 1000)
)
有什么想法吗?
答案 0 :(得分:2)
可以使用cumsum在不循环的情况下完成此操作。由于您有 final 余额并且想向后工作,因此我们需要反转列,取总和,从最终余额中减去,然后再次反转以使原始顺序保持不变。
df[1,-1] = rev(mar2019_closing_bal - cumsum(rev(colSums(df[-c(1,7),-1]))))
df[7,-1] = c(df[1,-(1:2)], mar2019_closing_bal)
df
placement_status_type sep2018 oct2018 nov2018 dec2018 jan2019 feb2019 mar2019
1 opening_bal 1899 1729 1542 1405 1329 1227 1133
2 New 97 96 101 76 117 124 70
3 Transfer -40 -40 -36 -27 -23 -39 -18
4 Reinstated 164 173 162 146 139 135 103
5 Suspended -221 -208 -206 -128 -168 -156 -173
6 Exit -170 -208 -158 -143 -167 -158 -115
7 closing_bal 1729 1542 1405 1329 1227 1133 1000
答案 1 :(得分:1)
这可以在for循环中完成,这是一个非常简单的forloop,可以很容易地将其编码为c ++或任何语言。因此,如果您尝试将其扩展到表中的某些怪物,则可以考虑一下。 但是出于合理的目的,这应该很好用。
df[nrow(df), ncol(df)] <- 1000 # Just putting in the known closing balance
for(j in ncol(df):2){
for(i in nrow(df):1){
if (i == 1) {
df[i, j] <- df[nrow(df), j] - sum(df[2:6, j])
}
if(i == nrow(df) & is.na(df[i, j])){
df[i, j] <- df[1, j + 1]
}
}
}
> df
placement_status_type sep2018 oct2018 nov2018 dec2018 jan2019 feb2019 mar2019
1 opening_bal 1899 1729 1542 1405 1329 1227 1133
2 New 97 96 101 76 117 124 70
3 Transfer -40 -40 -36 -27 -23 -39 -18
4 Reinstated 164 173 162 146 139 135 103
5 Suspended -221 -208 -206 -128 -168 -156 -173
6 Exit -170 -208 -158 -143 -167 -158 -115
7 closing_bal 1729 1542 1405 1329 1227 1133 1000