Question

I am working with a time series in which a simple root searching algorithm is needed to calculate a root by iteration. In order to do this I use the package rootSolve. However, I am having some problems trying to identify which function of the family apply to use when I want to extend this algorithm for multiple observations using the entire data set instead of doing it one at the time.

This is a simplification of the code written for 1 observation:

Z1, Z2, Z3,Z4 and are discount factors between 0 and 1
Z5 a percentage 

f<- function(x) (z1*(1-exp(-.25*x))
                     +z2*(exp(-.25*x)-exp(-.5*x))
                     +z3*(exp(-.5*x)-exp(-.75*x))
                     +z4*(exp(-.75*x)-exp(-x)))/
      (z1*exp(-.25*x)+z2*exp(-.5*x)+z3*exp(-.75*x)+z4*exp(-x))-z5

then I find a root  using
uni<-uniroot(f, c(0,1))

how would you write an apply function (I assume one is needed) to change Z1, Z2, Z3,Z4 and Z5 for vectors containing 780 observations each so I can find the roots of the function for each set of discounts and percentage? This might be straight forward but I haven’t been able to figure it out correctly.

Was it helpful?

Solution

Here one way to vectorize :

## zi should passed a additional parameter to f
f<- 
  function(x,z1,z2,z3,z4,z5) 
    (z1*(1-exp(-.25*x))
                 +z2*(exp(-.25*x)-exp(-.5*x))
                 +z3*(exp(-.5*x)-exp(-.75*x))
                 +z4*(exp(-.75*x)-exp(-x)))/
  (z1*exp(-.25*x)+z2*exp(-.5*x)+z3*exp(-.75*x)+z4*exp(-x))-z5

## wrap the unitroot function to make it function of only zi
root_f <-
  function(z1,z2,z3,z4,z5)
   uniroot(f, c(0,1),z1,z2,z3,z4,z5)

## use mapply to vectorize
mapply(root_f,Z1,Z2,Z3,Z4,Z5)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top