I'm attempting to roll a value forward using dplyr
's mutate()
and lag()
. I'm trying the below code to make it work. Instead of it working as I expect it to, I get ZEROs in the BegFund
column after the first row. I've tried using data.table shift()
with no luck, and stats::lag()
with no luck as well. Anyone have any ideas?
Below is a simplified example of what I'm attempting to do. Reproduces when I test.
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)
EDIT: Below is the output I'd like to get out of R for this. Please excuse the awful formatting, I'm very new at this.
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