Solved – Use of glm() and graph of regression line

generalized linear modelr

I am new to glms and have picked up the following text, I am trying to do the exercises and I'm a little stuck on exercises 4.5 question 4.1. The question states that a possible model for the data is a poisson distribution with parameter $\lambda_i = i^\theta$ where $i= (1,2,\dots,20)$ is the time index. I want to fit a poisson regression in R using the log link function, such that:
$$
g(\lambda_i)=\log(\lambda_i) = \beta_1 + \beta_2 \log i
$$
In R, I've done the following:

y<-c(1,6,16,23,27,39,31,30,43,51,63,70,88,97,91,104,110,113,149,159)
x<-1:20

I'm confused about the glm function, I'm pretty sure I should be fitting:

n1<-glm( y~log(x), family = poisson (link = log) )
plot(log(x),y)

What I'm finding hard to understand is when plotting the regression line, we should be plotting:

$$
\lambda_i =\exp ( \beta_1 + \beta_2 x_i)
$$
So we should have:

plot(log(x),y)
lines(log(x), exp(n1$fit))

which doesn't give a decent looking result, although

lines(log(x),n1$fit)

enter image description here

seems to be the right way to go, but doesn't make intuitive sense to me, aren't the fit values giving the linear part of the model??

Best Answer

The documentation clears this up. About halfway through it describes the object glm returns, which has the attribute

fitted.values   
  the fitted mean values, obtained by transforming the linear predictors by 
the inverse of the link function.

When you do n1$fit, R does partial name matching, and gives you n1$fitted.values.

Related Question