[R] In optim() function, second parameter in par() missing

David Winsemius dwinsemius at comcast.net
Mon Sep 5 18:21:38 CEST 2011


On Sep 5, 2011, at 11:41 AM, David Winsemius wrote:

>
> On Sep 5, 2011, at 10:30 AM, colstat wrote:
>
>> Hi,
>> First time using the optim(), can someone please tell me what I am  
>> doing
>> wrong?  The error looks like this
>>
>> Error in .Internal(pnorm(q, mean, sd, lower.tail, log.p)) :
>> 'sd' is missing
>>
>
> You should be using a textbook. Which one are you consulting?
>
>>
>> An example of the error
>> dat = c(20, 19, 9, 8, 7, 4, 3, 2)
>> dat_mu=mean(dat)
>> dat_s=sd(dat)
>>
>> max.func = function(dat, mu, sd) {
>>   pnorm(dat, mu, sd)
>> }
>>
>> optim(fn=max.func, dat=dat, par=c(mu=dat_mu, s=dat_s))
>>
>> I get sd is missing error.  If I wrote par=c(s=dat_s, mu=dat_mu) ,  
>> then it
>> tells me mu is missing.
>
> You constructed a function with two
< I meant to say that the function had three arguments (none of them  
"par") and you were incorrectly assuming the function would be able to  
find what was inside par despite not passing it.>

> arguments but optim only passes two argument to the objective  
> function. Build your objective function a) so that it accepts two  
> arguments

<And you don't actually need to use two args. You could set it up so  
that your max.fun gets the "dat" data from the calling environment.>

> and b) so that it returns one value. At the moment it does not do  
> either.

<But I remain convinced you need to be reading something didactic. I  
suggest Bolker's "Ecological Models and Data in R" ch 6 or Venables  
and Ripley's MASS4 ch 16. Bolker's text seems to start the reader out  
a bit more gently.  V&R's first example is a mixture model. I have a  
text I looked at Crawley's "R Book but it has no examples of the use  
of 'optim'. It did have a tiny example of using 'optimize' that I  
found difficult to follow because he uses attache and the data  
variables had been defined pages earlier.>
>
>
>> Can someone please help?
>>
>
> -- 
>
> David Winsemius, MD
> West Hartford, CT
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list