Search code examples
rnonlinear-optimizationnonlinear-functionsgamma

Solving a simply non linear system


For example i have this data:

x-c(73,6,77,81,91,120,150,61,65,68,18,20,23,12,14,18,23,26
+26,27,2,3,3,40,41,41,6,10,11,12,37,38,38,6,73,6,51)

and i want to calculate the a=shape and b=scale parameters of gamma distribution. I want to solve this non-linear system

a*b=m1
a*b^2+(a^2)*(b^2)=m2

The m1 and m2 are these:

m1<-sum(x)/length(x)
m2<-sum((x)^2)/length(x)

I can solve it with hand and with calculator, but i wanna know how to instantly solve this with R


Solution

  • R can do this quite easily

    library(nleqslv)
    f <- function(x) {
      a<-x[1]
      b<-x[2]
      c(a*b-m1,a*b^2+(a^2)*(b^2)-m2)
    }
    nleqslv(c(1,30), f)
    

    Output should look like:

    $`x`
    [1]  1.286486 30.595840
    
    $fvec
    [1] -9.663381e-13 -1.396074e-10
    
    $termcd
    [1] 1
    
    $message
    [1] "Function criterion near zero"
    
    $scalex
    [1] 1 1
    
    $nfcnt
    [1] 11
    
    $njcnt
    [1] 2
    
    $iter
    [1] 10
    

    You can make things more robust by providing gradients. Of course R can also estimate parameters for the gamma distribution directly (e.g. fitdistr from the MASS package).