R解决循环引用

R solving circular reference

我正在使用 Excel 中的公式,只有在启用迭代计算后才能给出正确的结果。

如何在R中解决这个迭代问题?

也许是这样的?

dat <- data.frame(
  indicator = rep(c(1,0,0), times = 4),
  interest = c(0,54,33,678,987,544,321,345,678,907,567,0)
)

intersolve <- function(indicator, interest){
  indicators = rev(cumsum(rev(indicator) == 1))
  sums = rev(tapply(interest, indicators, sum))
  interest_payment = rep(sums[-1], each = 3) * indicator
  return(interest_payment)
}

dat$interest_payment = intersolve(indicator = dat$indicator, interest = dat$interest)
dat

#    indicator interest interest_payment
# 1          1        0              765
# 2          0       54                0
# 3          0       33                0
# 4          1      678             1852
# 5          0      987                0
# 6          0      544                0
# 7          1      321             1930
# 8          0      345                0
# 9          0      678                0
# 10         1      907              567
# 11         0      567                0
# 12         0        0                0

编辑

以下函数自动检测 1 的模式。

intersolve2 <- function(indicator, interest){
  n = length(interest)
  indicators = rev(cumsum(rev(indicator) == 1))
  sums = rev(tapply(interest, indicators, sum))
  lens = rev(table(indicators))[-1]
  lens[length(lens)] = lens[length(lens)] + 1
  interest_payment = rep(sums[-1], times = lens) * indicator
  if (indicator[n] == 1){interest_payment[n]=interest[n]}
  return(interest_payment)
}