R code for IRRs
////////////////////////////////

paybackPeriod_f<-function(cashflows){
# assume the first one is an investment (negative)
 total<-cashflows[1]
 if(total>0)stop('The first cash flow should be negative')
 cashInflows<-cashflows[-1]
 n<-length(cashInflows)
  for(i in 1:n){
       total<-total+cashInflows[i]
      		 #print(total)
       if(total==0){
           return(i)
       }else if(total>0){
           partial<-total/cashInflows[i]
           return(i-1+partial)
       }
    }
}

We can have the following cashflows to test the above code. 
> cashflows<-c(-100,25,25,25,25,40,50)
> paybackPeriod_f(cashflows)
[1] 4
> cashflows<-c(-100,25,25,25,50,40,50)
> paybackPeriod_f(cashflows)
[1] 3.5
///////////////////////////////

present value (annuity) 
////////////////////////////
Definition of annuity:
   1) the same cash flows
   2) at the same interval,
   3) for n periods

 Example 1:                c       c 
   |-------|-------|-------|   ... |
   0       1       2       3      3+n-1
 Example 2:
           c       c      c        c
   |-------|-------|-------|   ... |
   0       1       2       3       n
 Example 3: (A general one)
                              c       c
   |-------|-------|---...----|   ... |
   0       1       2          k       k+n-1
   when k=1, example 3 --> example 2
   when k=3, example 3 --> example 1

 When cash flows happen at the end of each period and
      the first cash flow happens at the end of the first period
                    c         c             c        c         1
  pv(perpetuity) = ------ + -----  + ... + ----    = ---[1 -  ----]
                  (1+R)^1   (1+R)^2       (1+R)^n    R       (1+R)^n
   where C is the period cash flow
         R is the period discount rate
         n is the number of periods

  see .ice(26) for one example. 
/////////////////////////

pv(annuity): several ways to estimate 
////////////////////////////
Method I: apply the follwoing formula
          see an example 
             .ice(26)

Method II:   Write a loop to apply the following formula n times
             pv_f<-function(f,r,n)fv/(1+r)^n

            a) a for()  loop
            b) a while() loop
            c) a repeat() loop
            d) when the first cash flow happens at the 10th period 

/////////////////////////