[R] Using nlm or optim

Ravi Varadhan rvaradhan at jhmi.edu
Thu Jul 8 15:48:58 CEST 2010


Hi,

When you report errors please send a reproducible example that will allow us to better help you.  At a minimum, you should cut and paste the actual call and the error message.

I think the problem is that you should only have parameters as arguments, i.e. only c and z should be in the argument list to nll().   

This works:

Predict <- function(M,c,z){
v = c*M^z
return(v)
}

nll <- function(c,z){
n<-length(M)
logl<- -.5*n*log(2*pi) -.5*n*log(s) - (1/(2*s))*sum((V-Predict(M,c,z))^2)
return(-logl)
}

M <- rexp(130)
V <- runif(130)
s <- 200

mle(nll,start=list(c=0.01,z=2.1)) 

> mle(nll,start=list(c=0.01,z=2.1)) 

Call:
mle(minuslogl = nll, start = list(c = 0.01, z = 2.1))

Coefficients:
          c           z 
 0.48547691 -0.01018601 
>

Hope this helps,
Ravi.
____________________________________________________________________

Ravi Varadhan, Ph.D.
Assistant Professor,
Division of Geriatric Medicine and Gerontology
School of Medicine
Johns Hopkins University

Ph. (410) 502-2619
email: rvaradhan at jhmi.edu


----- Original Message -----
From: Anita Narwani <anitanarwani at gmail.com>
Date: Wednesday, July 7, 2010 9:11 pm
Subject: [R] Using nlm or optim
To: r-help at r-project.org


> Hello,
>  I am trying to use nlm to estimate the parameters that minimize the
>  following function:
>  
>  Predict<-function(M,c,z){
>  + v = c*M^z
>  + return(v)
>  + }
>  
>  M is a variable and c and z are parameters to be estimated.
>  
>  I then write the negative loglikelihood function assuming normal errors:
>  
>  nll<-function(M,V,c,z,s){
>  n<-length(Mean)
>  logl<- -.5*n*log(2*pi) -.5*n*log(s) - (1/(2*s))*sum((V-Predict(Mean,c,z))^2)
>  return(-logl)
>  }
>  
>  When I put the Mean and Variance (variables with 136 observations) 
> into this
>  function, and estimates for c,z, and s, it outputs the estimate for the
>  normal negative loglikelihood given the data, so I know that this works.
>  
>  However, I am unable to use mle to estimate the parameters c, z, and 
> s. I do
>  not know how or where the data i.e. Mean (M) and Variance (V) should 
> enter
>  into the mle function. I have tried variations on
>  
>  mle(nll,start=list(c=0.01,z=2.1,s=200)) including
>  mle(nll,start=list(M=Mean,V=Var, c=0.01,z=2.1,s=200))
>  
>  I keep getting errors and am quite certain that I just have a syntax 
> error
>  in the script because I don't know how to enter the variables into MLE.
>  
>  Thanks for your help,
>  Anita.
>  
>  	[[alternative HTML version deleted]]
>  
>  ______________________________________________
>  R-help at r-project.org mailing list
>  
>  PLEASE do read the posting guide 
>  and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list