I'm trying to use the optim function in R to optimise three parameters in a model, but can't figure out how to get it to search over a range of values, as is possible using the "optimize" function. I've tried doing it using a for loop, and this was the most successful of my attempts but it seems to stop at values of 355 for some reason, Ideally I'd like to try higher combinations than this. As well as this I have tried writing functions that call optim many times, tried vectorising and tried just putting list values into the "par" arguments within optim however all these attempts produced the error message
"unable to evaluate at initial parameters".
Long short does anyone know how I can use the optim function to search over a range of values for parameters as the "optimize" function will???
Any help or pointers would be GREATLY appreciated!!!
My code looks like: It's three maximum likelihood functions for corresponding scale and then three attempts at using optim!
rm(list=ls())
load('Dat.RData')
mean(dat)
var(dat)
loglike<-function(par,dat,scale)
{ ptp<-dat[1:length(dat)-1]
ptp1<-dat[2:length(dat)]
r<-par['r']
k<-par['k']
sigma<-par['sigma']
if(scale=='log')
{
return(sum(dnorm(log(ptp1)-log(ptp)*exp(r-(ptp/k)),mean=0,sd=sigma,log=T)))
}
if (scale=='sqrt')
{
return(sum(dnorm(sqrt(ptp1)-sqrt(ptp)*exp(r-(ptp/k)),mean=0,sd=sigma,log=T)))
}
if (scale=='linear')
{
return(sum(dnorm(ptp1-ptp*exp(r-(ptp/k)),mean=0,sd=sigma,log=T)))
}
}
sqrts<-c()
for(i in 1:4000){
sqrts[i]<-optim(par=c(r=i,k=i,sigma=i),fn=loglike,dat=dat,scale='sqrt',method='Nelder-Mead',control=list(fnscale=-1))
}
logs<-c()
for(i in 1:4000){
logs[i]<-optim(par=c(r=i,k=i,sigma=i),fn=loglike,dat=dat,scale='log',method='Nelder-Mead',control=list(fnscale=-1))
}
lins<-c()
for(i in 1:4000){
lins[i]<-optim(par=c(r=i,k=i,sigma=i),fn=loglike,dat=dat,scale='linear',method='Nelder-Mead',control=list(fnscale=-1))
}
Many thanks!!
head(dput(dat))
it will help people here reconstruct a portion of your data so they can run the code more easily – Simon O'Hanlon