How can I print out the design matrix from lm in R?

Viewed 4007

Assume x2-x4 are continuous predictors occupying one column each in the design matrix created using lm() in R. I want to include x1 a categorical variable that has 3 levels.

Regression R code:
fit <- lm(y~as.factor(x1)+x2+x3+c4,data=mydata)

How can I print the design matrix from lm() in R and what would it look like? I need to know the default coding used in R so I can write contrast statements properly.

2 Answers

I think the model.matrix() function is what you're after.

As kjetil b halvorsen says you can specify the model in the argument. Or you can just hand model.matrix the defined model.

fit <- lm(y~as.factor(x1)+x2+x3+c4,data=mydata)
model.matrix(fit)

You can even get a design matrix for new data: model.matrix(fit, data=newdata)

The comment by kjetil b halvorsen helped me the most:

call res <- lm() with the argument x=TRUE then the design matrix will be returned in the model object res Then call str(res) to see the structure of res, and you will now how to get the design matrix from it. But easier is to call model.matrix(y ~ x + f, data=...) with the same model formula you use in lm.

Related