在mutate()中的r-dplyr-lag()用于向前滚动值



我正试图使用dplyrmutate()lag()向前滚动一个值。我正在尝试下面的代码使其工作。它并没有像我期望的那样工作,而是在第一行之后的BegFund列中得到了零。我尝试过使用data.table shift(),但没有运气,使用stats::lag()也没有运气。有人有什么想法吗?

下面是我尝试做什么的一个简化例子。在我测试时复制。

library(dplyr) #  0.4.3
payments <- 1:10
fund.start <- 1000
payment.percent <- .05
fund.value <- data.frame(payments)
fund.value <- fund.value %>%
  transmute(Payment = payments) %>%
  mutate(EndFund = 0) %>%
  mutate(BegFund = ifelse(Payment == 1, fund.start, lag(EndFund, 1)),
         PmtAmt = BegFund * payment.percent,
         EndFund = BegFund - PmtAmt) %>%
  select(Payment, BegFund, PmtAmt, EndFund)
head(fund.value)

编辑:下面是我想从R中得到的输出。请原谅格式太糟糕了,我对此很陌生。

Payment  BegFund          PmtAmt        EndFund
1        1000             50            950
2        950              47.5          902.5
3        902.5            45.125        857.375
4        857.375          42.86875      814.50625
5        814.50625        40.7253125    773.7809375
6        773.7809375      38.68904688   735.0918906

这里有一种方法:

EndFund = fund.start * (1 - payment.percent) * (1-payment.percent)^(payments-1L)
BegFund = c(fund.start, head(EndFund, -1L))
PymtAmt = BegFund - EndFund

刚刚注意到@Eddi也在评论中对此进行了报道。

我知道这不是OP想要的方式,但它可能有助于

fund.value <- data.frame(payments, BegFund=0, PmtAmt=0,EndFund=0)
fund.value$BegFund[1]<-fund.start
fund.value$PmtAmt[1] = fund.value$BegFund[1] * payment.percent
fund.value$EndFund[1] = fund.value$BegFund[1] - fund.value$PmtAmt[1]
for(i in 2:dim(fund.value)[1]){
  fund.value$BegFund[i]<-fund.value$EndFund[i-1]
  fund.value$PmtAmt[i] = fund.value$BegFund[i] * payment.percent
  fund.value$EndFund[i] = fund.value$BegFund[i] - fund.value$PmtAmt[i]
}  

退出是

  payments   BegFund   PmtAmt  EndFund
1        1 1000.0000 50.00000 950.0000
2        2  950.0000 47.50000 902.5000
3        3  902.5000 45.12500 857.3750
4        4  857.3750 42.86875 814.5063
5        5  814.5063 40.72531 773.7809
6        6  773.7809 38.68905 735.0919

最新更新