[R] Trying to write a linear regression using MLE and optim()

Gabor Grothendieck ggrothendieck at gmail.com
Tue May 31 08:06:32 CEST 2005


On 5/30/05, Ajay Shah <ajayshah at mayin.org> wrote:
> 
> I wrote this:
> 
> # Setup problem
> x <- runif(100)
> y <- 2 + 3*x + rnorm(100)
> X <- cbind(1, x)
> 
> # True OLS --
> lm(y ~ x)
> 
> # OLS likelihood function --
> ols.lf <- function(theta, K, y, X) {
>  beta <- theta[1:K]
>  sigma <- exp(theta[K+1])
>  e <- (y - X%*%beta)/sigma
>  logl <- sum(log(dnorm(e)))
>  return(logl)
> }
> 
> optim(c(2,3,0), ols.lf, gr=NULL,
>      method="BFGS", lower=-Inf, upper=Inf,
>      control=list(trace=2, fnscale=-1),
>      # Now for the "..." stuff
>      K, y, X)

The last line should be:

K=K, y=y, X=X)

and also you have to set K.


> 
> 
> I get:
> 
> Error in fn(par, ...) : argument "X" is missing, with no default
> In addition: Warning message:
> numerical expression has 100 elements: only the first used in: 1:K
> Execution halted
> 
> If someone can show me the way, it'll be most appreciated. :-)
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list