Tell me more ×
Cross Validated is a question and answer site for statisticians, data analysts, data miners and data visualization experts. It's 100% free, no registration required.

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

share|improve this question

4 Answers

up vote 8 down vote accepted

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)
share|improve this answer
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
1  
@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

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"
share|improve this answer
(+1) Very handy. – chl Dec 17 '10 at 7:47

May be it's a little bit hackish but you can do :

n <- length(coefficients(model))
share|improve this answer

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.)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.