views:

212

answers:

1

I am trying to write a function that uses Newton's method (coefficients+(inverse hessian)*gradient) to iteratively find the coefficients for a loglinear model.

I am using the following code:

 ##reading in the data
    dat<-read.csv('hw8.csv')
    summary(dat)
    # data file containing yi and xi
    attach(dat)
    ##Creating column of x's
    x<-cbind(1,xi)

    mle<-function(c){
     gi<- 1-yi*exp(c[1]+c[2]*xi)
     hi<- gi-1
     H<- -1*(t(x)%*%hi%*%x)
     g<-t(x)%*%gi
     c<-c+solve(H)%*%g
      return(c)
    }

    optim(c(0,1),mle,hessian=TRUE)

When I run the code, I get the following error:

Error in t(x) %*% hi %*% x : non-conformable arguments
RMate stopped at line 29

Given that the formula is drawn from Bill Greene's problem set, I don't think it is a formula problem. I think I am doing something wrong in passing my function.

How can I fix this?
Any help with this function would be much appreciated.

+2  A: 

As Jonathan said in the comments, you need proper dimensions:

R> X <- matrix(1:4, ncol=2)
R> t(X) %*% X 
     [,1] [,2]
[1,]    5   11
[2,]   11   25
R>

But you also should use the proper tools so maybe look at the loglin function in the stats package, and/or the loglm function in the MASS package. Both will be installed by default with your R installation.

Dirk Eddelbuettel