在R中计算IRR时如何合并if语句? [英] How can I incorporate if statement when calculating IRR in R?

查看:261
本文介绍了在R中计算IRR时如何合并if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来计算IRR的一个简单函数。但是,当所有现金流量都为负并且返回未解除错误(npv,c(0,1),cf = cf)时,有一些事件发生:f()值不是符号相反的终点。我有什么方法可以把if语句放到IRR不能计算的时候,R只返回0?

This is a simple function I use to calculate IRR. However, there are incidences when all cash flows are negative and return "Error in uniroot(npv, c(0, 1), cf = cf) : f() values at end points not of opposite sign." Is there any way I can put if statement so that when IRR can't be computed, R simply returns 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)


推荐答案

您可以使用全部函数:

irr <- function(cf) {
              if(all(cf < 0)) return(0)
              uniroot(npv, c(0,1), cf=cf)$root
       }




  • 如果所有函数返回TRUE,则返回函数将返回0然后退出函数。

  • 如果所有函数返回FALSE,则 uniroot 函数将像以前一样运行。

    • If the all function returns TRUE, the return function will return 0 and then exit the function.
    • If the all function returns FALSE, then the uniroot function will run as it did previously.
    • 这篇关于在R中计算IRR时如何合并if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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