gpt4 book ai didi

r - 在 R 中计算 IRR 时如何合并 if 语句?

转载 作者:行者123 更新时间:2023-12-01 11:25:28 32 4
gpt4 key购买 nike

这是我用来计算 IRR 的一个简单函数。然而,当所有现金流量均为负数并返回“uniroot(npv, c(0, 1), cf = cf) 中的错误:端点处的 f() 值不是相反符号时,会发生这种情况。”有什么方法可以放置 if 语句,以便在无法计算 IRR 时,R 仅返回 0?

npv<-function(i,cf,t=seq(along=cf)) sum (cf/(1+i)^t)
irr <- function(cf) {uniroot(npv, c(0,1), cf=cf)$root }
irr(cf)

最佳答案

您可以使用all 函数:

irr <- function(cf) {
if(all(cf < 0)) return(0)
uniroot(npv, c(0,1), cf=cf)$root
}
  • 如果all函数返回TRUE,return函数将返回0,然后退出函数。
  • 如果 all 函数返回 FALSE,则 uniroot 函数将像以前一样运行。

关于r - 在 R 中计算 IRR 时如何合并 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37707952/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com