我在Excel中使用公式,只有在启用迭代计算后才会给出正确的结果。
如何解决R
中的这个迭代问题?
答案 0 :(得分:0)
也许是这样的?
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)
}