Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integrate() function giving incorrect results in R

Tags:

function

r

I tried to use integrate function in two slightly different manner. Both resulted in different answers.

dgpareto = Vectorize(function(x,a,l,k){
   gamma(a+k)*(l^a)*(x^(k-1))/(gamma(a)*gamma(k)*((l+x)^(a+k)))
})
pgpareto = function(q,a,l,k){
   integrate(dgpareto,lower = 0,upper = q,a=a,l=l,k=k)$value
}
pgpareto2 = function(q,a,l,k){
   integrate(dgpareto,0,q,a=a,l=l,k=k)$value
}
pgpareto(5,2,1,1)
#[1] 0.9722222
pgpareto2(5,2,1,1)
#[1] -0.3055556

The integrate() gives the correct / expected result when the limits are specified by lower = 0 and upper = q but gives incorrect results without it. lower and upper are 2nd and 3rd input to integrate so I expected that I can use their input values without naming them explicitly. Whats the issue here? What am I doing wrong?

like image 894
Bhavya Shah Avatar asked Nov 06 '25 06:11

Bhavya Shah


1 Answers

It's a subtle annoyance and it has to do with argument partial matching. Consider this:

integrate(dnorm, u = 1, l = 0)$value
#[1] 0.3413447

As you can see, R partially matched the u argument as upper and l for lower.

Same happened in your case. You meant the l argument as the integrand function argument; instead, R intended that as the lower argument of integrate. So 0 became the first non named argument (and so upper), while the q value was used as the l argument of the integrand function.

like image 74
nicola Avatar answered Nov 09 '25 10:11

nicola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!