[R] trouble using optim for maximalisation of 2-parameter function

Matthias Kohl Matthias.Kohl at stamats.de
Sun Jul 19 20:40:41 CEST 2009


try:

# first argument of llik.nor has to be the parameter
llik.nor<-function(theta,x){mu<-theta[1];sig<-theta[2];-length(x)*log(sqrt(2*pi))-length(x)*log(sig)-(1/(2*sig**2))*sum((x-mu)**2)}

# optim by default does minimization
# setting fnscale = -1 one obtains a maximization problem
optim(c(1,5), llik.nor, x=x, control = list(fnscale = -1))

hth,
Matthias

Anjali Sing schrieb:
> Hello, I am having trouble using "optim".
>
> I want to maximalise a function to its parameters [kind of like: univariate
> maximum likelihood estimation, but i wrote the likelihood function myself
> because of data issues ]
>
> When I try to optimize a function for only one parameter there is no
> problem:
>
> llik.expo<-function(x,lam){(length(x)*log(lam))-(length(x)*log(1-exp(-1*lam*
> *cons*)))-lam*sum(x)}
>
> cons<-
>
> data<-c(.............)
>
> expomx<-optimize(llik.expo,c(0,100),maximum=TRUE,tol=0.0001,x=data)
> expomx
>
>
>  To optimize to two parameters you can't use "optimize", so I tried the
> following to test my input:
>
>   
> llik.nor<-function(x,theta){mu<-theta[1];sig<-theta[2];-length(x)*log(sqrt(2*pi))-length(x)*log(sig)-(1/(2*sig**2))*sum((x-mu)**2)}
>   
>> x<-c(-1,4,6,4,2)
>> normx<-optim(c(1,20),llik.nor)
>>     
>
> the output should be close to
> parameters: mu=3 and sigma=2.366
> [This I calculated by hand to compare with the output]
>
> but in stead of output I get an error:
> Error in fn(par, ...) : argument "theta" is missing, with no default
>
> I don't understand why this happened? I hope someone can help me with this
> for I am still a [R]ookie.
>
> Kind regards,
> Sonko Lady  [Anjali]
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>   

-- 
Dr. Matthias Kohl
www.stamats.de




More information about the R-help mailing list