sh2657 sh2657 - 4 years ago 88
R Question

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 }

lmo lmo
Answer Source

You could use the all function:

irr <- function(cf) {
              if(all(cf < 0)) return(0)
              uniroot(npv, c(0,1), cf=cf)$root
  • 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download