Search code examples
rdata-analysisnormal-distribution

It is possible to solve equation R that are not linear?


I want to build a function that takes E[x] and Var[X] and give me the mean and standard error of a univariate lognormal variable.

E[x] = exp(mu + theta) 
Var[x] =  exp(2*mu + theta)*(exp(theta) - 1)

The function would take E[x] and Var[x] as input and as output would give me theta and mu


Solution

  • There are several packages that provide ways and means to solve a system of nonlinear equations. One of these is nleqslv.

    You nee to provide a function that function that returns the differences between the actual value of the equations and the desired value.

    Load package nleqslv and define the following function

    library(nleqslv)
    
    f <- function(x,Ex,Varx) {
        y<- numeric(length(x))    
        mu <- x[1]
        theta <- x[2]
        y[1] <- exp(mu+theta) - Ex
        y[2] <- exp(2*mu+theta)*(exp(theta)-1) - Varx
    
        y
    }
    

    The vector x in the function contains the values of mu and theta. An example with Ex=2 and Varx=3 and some random starting values

    xstart <- c(1,1)
    nleqslv(xstart,f,Ex=2,Varx=3)
    

    gives the following

    $x
    [1] -0.6931472  1.3862944
    
    $fvec
    [1] -8.095125e-11 -8.111645e-11
    
    $termcd
    [1] 1
    
    $message
    [1] "Function criterion near zero"
    
    $scalex
    [1] 1 1
    
    $nfcnt
    [1] 31
    
    $njcnt
    [1] 2
    
    $iter
    [1] 22
    

    See the manual of nleqslv for the meaning of the different elements of the return value of nleqslv.

    If you want to investigate the effect of the different solving methods try this

    testnslv(xstart,f,Ex=2,Varx=3)