新答案:你可以做相同的操作组,并考虑不同类型的交易如下:
df1 <- transform(df1, Amount = Amount*c(-1,1,0)[(Type %in% c(85,90)) + 1L])
df1 <- transform(df1, Balance = ave(df1$Amount, df1$ID, FUN = function(x) round(cumsum(x),2)))
或者:
library(dlyr)
df1 %>%
group_by(ID) %>%
mutate(Amount = Amount*c(-1,1)[(Type %in% c(85,90)) + 1L],
Balance = round(cumsum(Amount),2))
给予:
Source: local data frame [12 x 5]
Groups: ID [2]
ID Type Type_Description Amount Balance
(int) (int) (fctr) (dbl) (dbl)
1 41 85 incoming_transaction 100.00 100.00
2 41 55 outgoing_transaction -76.60 23.40
3 41 55 outgoing_transaction -23.40 0.00
4 41 90 incoming_transaction 24.10 24.10
5 41 55 outgoing_transaction -14.19 9.91
6 41 63 Sweep_Off_Amount -9.91 0.00
7 42 85 incoming_transaction 100.00 100.00
8 42 55 outgoing_transaction -76.60 23.40
9 42 55 outgoing_transaction -23.40 0.00
10 42 90 incoming_transaction 24.10 24.10
11 42 55 outgoing_transaction -14.19 9.91
12 42 63 Sweep_Off_Amount -9.91 0.00
使用 data.table 你可以:
library(data.table)
setDT(df1)[, Amount := Amount*c(-1,1)[(Type %in% c(85,90)) + 1L]
][, Balance := round(cumsum(Amount),2), by = ID][]
旧答案:如果我理解正确,您想从Trs_Amount 计算Balance,其中Transaction_Type==85 表示传入事务,Transaction_Type==55 表示传出事务。为此,您可以使用如下条件 cumsum:
mydf <- transform(mydf, Balance = round(cumsum(ifelse(Transaction_Type==85,
Trs_Amount,
-1*Trs_Amount)),2))
给出:
> mydf
ID Transaction_Type Trs_Amount Balance
1 121 85 100.00 100.00
2 121 55 21.52 78.48
3 121 55 36.01 42.47
4 121 55 15.57 26.90
5 121 55 2.02 24.88
6 121 55 23.49 1.39
7 121 55 1.39 0.00
您可以使用 dplyr 包:
library(dplyr)
mydf %>%
mutate(Balance = round(cumsum(ifelse(Transaction_Type==85,
Trs_Amount,
-1*Trs_Amount)),
2))
给出相同的结果。一个稍微替代的实现是:
mydf %>%
mutate(Trs_Amount = Trs_Amount*c(-1,1)[(Transaction_Type==85) + 1L],
Balance = round(cumsum(Trs_Amount),2))
给出:
ID Transaction_Type Trs_Amount Balance
1 121 85 100.00 100.00
2 121 55 -21.52 78.48
3 121 55 -36.01 42.47
4 121 55 -15.57 26.90
5 121 55 -2.02 24.88
6 121 55 -23.49 1.39
7 121 55 -1.39 0.00