# Get the number of parameters of a linear model

Is there a way to get the number of parameters of a linear model like that?

model <- lm(Y~X1+X2)

I would like to get the number 3 somehow (intercept + X1 + X2). I looked for something like this in the structures that lm, summary(model) and anova(model) return, but I didn't figure it out. In case I don't get an answer, I'll stick on

dim(model.matrix(model))[2]

Thank you

-

Try something like:

> x <- replicate(2, rnorm(100))
> y <- 1.2*x[,1]+rnorm(100)
> summary(lm.fit <- lm(y~x))
> length(lm.fit$coefficients) [1] 3 > # or > length(coef(lm.fit)) [1] 3 You can have a better idea of what an R object includes with > str(lm.fit) - Thank you. In the meanwhile I realized that I also need the number of observations (n). One way is this: dim(model.matrix(model))[1] Can you suggest another way ? – Brani Dec 15 '10 at 21:28 @Brani Try nrow(na.omit(cbind(y,x1,x2))) (following your notation) or length(lm.fit$model$y), to get the number of observations used when estimating model parameters. BTW, you're better off making a data.frame, e.g. df <- data.frame(y,x1,x2), and then use lm(y ~ ., data=df). – chl Dec 15 '10 at 23:55 add comment A more general approach is to use the logLik() function. It returns an object with the attribute df that gives the fitted models degrees of freedom. The benefit of this approach is that it works with many other model classes (including glm). In the case of ordinary linear regression (lm) this corresponds to the number of parameters + 1 for the estimate of the error variance. From the logLik documentation: For "lm" fits it is assumed that the scale has been estimated (by maximum likelihood or REML), and all the constants in the log-likelihood are included. You can get the number of observations this way too. > X1 <- rnorm(10) > X2 <- rnorm(10) > Y <- X1 + X2 + rnorm(10) > model <- lm(Y~X1+X2) > ll <- logLik(model) > attributes(ll)$nall
[1] 10

$nobs [1] 10$df
[1] 4

$class [1] "logLik" - (+1) Very handy. – chl Dec 17 '10 at 7:47 add comment May be it's a little bit hackish but you can do : n <- length(coefficients(model)) - add comment I think you could use the component lm.fit$rank or else subtract lm.fit\$df.residual from the sample size to get what you want. (I assume you want the number of free parameters.)

-