簡體   English   中英

R 之前計算的 function 的滯后值

[英]R Lag value of previous calculated function

我正在嘗試使用前一行的滯后值,該值需要從前一行計算(除非它的第一個條目)。

我正在嘗試類似的東西:

test<-data.frame(account_id=c(123,123,123,123,444,444,444,444),entry=c(1,2,3,4,1,2,3,4),beginning_balance=c(100,0,0,0,200,0,0,0),
                 deposit=c(10,20,5,8,10,12,20,4),running_balance=c(0,0,0,0,0,0,0,0))

test2<-test %>%
  group_by(account_id) %>%
  mutate(running_balance = if_else(entry==1, beginning_balance+deposit,
                                   lag(running_balance)+deposit))

print(test2)

流動余額應為110,130,135,143,210,222,242,246

對於每個account_id ,您可以添加first一個beginning_balance和累積deposit總和。

library(dplyr)

test %>%
  group_by(account_id) %>%
  mutate(running_balance = first(beginning_balance) + cumsum(deposit))


#  account_id entry beginning_balance deposit running_balance
#       <dbl> <dbl>             <dbl>   <dbl>           <dbl>
#1        123     1               100      10             110
#2        123     2                 0      20             130
#3        123     3                 0       5             135
#4        123     4                 0       8             143
#5        444     1               200      10             210
#6        444     2                 0      12             222
#7        444     3                 0      20             242
#8        444     4                 0       4             246

使用data.table同樣的事情:

library(data.table)
setDT(test)[, running_balance := first(beginning_balance) + cumsum(deposit), account_id]

對每個唯一的 account_id 使用 for 循環,並為每個 id 添加累積總和。

for ( i in unique (test$account_id)) {

  test$running_balance [test$account_id == i] <- cumsum(test$beginning_balance[test$account_id == i]+test$deposit[test$account_id == i])

}

print (test)

     account_id entry beginning_balance deposit running_balance
1        123     1               100      10             110
2        123     2                 0      20             130
3        123     3                 0       5             135
4        123     4                 0       8             143
5        444     1               200      10             210
6        444     2                 0      12             222
7        444     3                 0      20             242
8        444     4                 0       4             246

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM