[R] Problems with integrate

From: Tolga Uzuner <tolga_at_coubros.com>
Date: Sun 11 Dec 2005 - 04:22:02 EST


Having a weird problem with the integrate function.

I have a function which calculates a loss density: I'd like to integrate it to get the distribution.

The loss density function is:

# the second derivative of the PDF
# p is the default probability of the pool at which we are evaluating the lossdensity
# Beta is the correlation with the market factor as a function of K # R is the recovery rate

C=qnorm(p) # default threshold for the pool

return(alpha0+(alpha10+alpha11*fd(K,Beta))*fd(K,Beta)+alpha20*fd2(K,Beta)) }

Beta needs to be passed in as a function:


Now, when I try out lossdensity, it works fine:

> lossdensity(.02,Beta,.4)

[1] 0.1444915

I defined lossdistribution as:

lossdistribution<-function(p,Beta,R=0.4){ integrate(function(x)lossdensity(x,Beta,R),0.0000000000001,p)}

But this gives a weird error:

> lossdistribution(0.1,Beta)

Error in "[<-"(`*tmp*`, k, i, value = c(4.29850518211428, 0, 0, 0, 0, :

        number of items to replace is not a multiple of replacement length

What's interesting is, if I use the area function from library(MASS), it works:

> lossdistribution<-function(p,Beta,R=0.4){
+ area(function(x){lossdensity(x,Beta,R)},0.00001,p)}
> lossdistribution(.02,Beta,.4)

[1] 0.0002177284

I could just go ahead and use that, but would like to understand why integrate is not working.

Thanks in advance,

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sun Dec 11 04:31:05 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:41:35 EST