rif-statementirr

How can I incorporate if statement when calculating IRR in R?


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)

Solution

  • You could use the all function:

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