Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize a function of a function in r

I would like to minimize the mean squared error (the mse() in the hydroGOF Package might be used) between modeled and observed spreads. The function is defined as:

    KV_CDS <- function(Lambda, s, sigma_S){
     KV_CDS = (Lambda * (1 + s)) / exp(-s * sigma_S) - Lambda^2)
}

The goal is to minimize mse between KV_CDS and C by leaving Lambda a free parameter in the KV_CDS function.

df <- data.frame(C=c(1,1,1,2,2,3,4),
                 Lambda=c(0.5),s=c(1:7),
                 sigma_S=c(0.5,0.4,0.3,0.7,0.4,0.5,0.8),
                 d=c(20,30,40,50,60,70,80), 
                 sigma_B=0.3, t=5, Rec=0.5, r=0.05)
like image 577
New2R Avatar asked Feb 28 '13 17:02

New2R


1 Answers

You'll need to write a function to minimise that calculates the mean squared error for this particular case, e.g.:

calcMSE <- function (Lambda) 
{
        d <- df # best not to use -df- as a variable because of confusion with
                # degrees of freedom
        err <- d$C - KV_CDS(Lambda, d$s, d$sigma_S, d$d, d$sigma_B, d$t, d$Rec, d$r)
        sum(err^2) / length(err)
}

... and then you can use optimize(), like this for instance (you need to specify the range of possible values for Lambda -- incidentally not an ideal name because it implies that it could be a function when it is actually just a variable):

optimize(calcMSE,c(0,1))

I couldn't do the complete test because I didn't have pbivnorm installed but this ought to do it for you.

like image 70
Simon Avatar answered Oct 01 '22 13:10

Simon