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
 A: 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"

A: May be it's a little bit hackish but you can do :
n <- length(coefficients(model))

A: 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)

A: 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.)
A: The R function logLik seems to be an attractive solution to extract model degree of freedom in general, since it can be applied to many model objects including lm, glm, nls, Arima to name a few. 
But the df of attributes(logLik(obj)) seems to be 1 larger than the true value. So use it with caution. 
