Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewing an object produced by `glm` as a list in R

Tags:

r

glm

In R, the regression function glm produces an object of class glm which is a list.

As it is a list, I should be able to view an object of class glm as list without any formatting going on. However, as.list doesn't seem to do this.

For example, if fit is a model fitted by the function glm:

> as.list(fit)

Call:  glm(formula = V4 ~ V3 + V2 + V1, family = Gamma, data = data)

Coefficients:
(Intercept)           V3           V2           V1  
      1.349        1.593        1.577        1.127  

Degrees of Freedom: 9999 Total (i.e. Null);  9996 Residual
Null Deviance:      2137 
Residual Deviance: 2048         AIC: -30180

On the other hand, other functions that apply to list work correctly, such as names which will produce the 30 names of the associated list.

Also, I can view individual elements in the same manner that I would for any other list:

> fit$coefficients
(Intercept)          V3          V2          V1 
   1.349282    1.593067    1.576868    1.127067 

Is there any pre-existing function that will allow me to view fit in its list form without formatting?

As I said above, I could build my own function using the names of the list, but that seems unnecessary for such a simple task.

like image 644
Jon Claus Avatar asked Mar 23 '23 10:03

Jon Claus


1 Answers

Although fit is a list, it has class glm, so auto-printing it dispatches the print.glm() print method. As shown below, as.list() preserves the object's class, so doesn't help you at all.

fit <- glm(speed~dist, data=cars)  ## A silly example
class(fit)
# [1] "glm" "lm" 
class(as.list(fit))
# [1] "glm" "lm" 
exists("print.glm")
# [1] TRUE

Either of the following will print fit as a list.

unclass(fit)        ## Returns and immediately auto-prints object of class "list"
                    ## using print.default() 

print.default(fit)  ## Bypasses method dispatch, directly calling desired print
                    ## method
like image 76
Josh O'Brien Avatar answered Apr 06 '23 01:04

Josh O'Brien