I am using optim
to fit various probability distributions to two given tertiles t1
and t2
. The following function works, where qfun
is the quantile function of the distribution and par_start
gives the initial values of the parameters of the distribution:
tertile_fit <- function(t1, t2, qfun, par_start) {
gapfn <- function(par, t1, t2, qfun) {
a <- t1 - do.call(qfun, as.list(c(1/3, par)))
b <- t2 - do.call(qfun, as.list(c(2/3, par)))
a ^ 2 + b ^ 2
}
result <- optim(par = par_start, gapfn, t1 = t1, t2 = t2, qfun = qfun)
if (result$convergence != 0) {
stop("Optmisation failed")
} else {
result$par %>%
as.list
}
}
The length of par_start
determines how many of the distribution's parameters are varied in the optimisation but very much restricts the choice: if length(par_start) = 3
for example then the optimisation will be made over the first 3 parameters in formals(qfun)
.
My problem is that for some distributions I want to be able to choose which parameters are to be fixed. I could solve that problem if I were writing specific code for each distribution by amending the do.call
lines in gapfn
, to include the names and values of the parameters I fix, for example:
do.call(qfun, as.list(c(1/3, mean = 0, par)))
with par
now the parameters that are allowed to vary.
But what I want is a function that can take any probability distribution and fix named parameters. It might look something like this:
new_tertile_fit <- function(t1, t2, qfun, fixed_params, par_start)
where fixed_params
is a data.frame(?) or a list(?) giving the names of the parameters and the values at which they are fixed.
What is giving me trouble is extracting that information from fixed_params
so that the do.call
lines can include the specific statements along the lines par1 = 2
if par1
is one of the parameters of the distribution being fitted.