mutate()内的dplyr lag()用于向前滚动值 [英] dplyr lag() inside mutate() for rolling values forward

查看:162
本文介绍了mutate()内的dplyr lag()用于向前滚动值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 dplyr mutate() lag()。我正在尝试以下代码以使其正常工作。在第一行之后的 BegFund 列中,我没有达到预期的效果。我试过使用 data.table shift()没有运气,而 stats :: lag()没有运气运气也好。有人有任何想法吗?

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)

编辑:以下是我想退出R的输出。请原谅糟糕的格式,我对此很陌生。

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


推荐答案

这里是一种方法:

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

只是注意到@Eddi也涵盖了在评论中。

Just noticed that @Eddi also has covered this under comment.

这篇关于mutate()内的dplyr lag()用于向前滚动值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆