[R] How do I obtain the design matrix of an lm()?
Gavin Simpson
gavin.simpson at ucl.ac.uk
Wed Oct 10 12:44:58 CEST 2007
On Tue, 2007-10-09 at 20:04 +0530, Ajay Shah wrote:
> I am using the clever formula notation of R to first do an OLS. E.g. I
> say
>
> m <- lm(y ~ x + f)
>
> where f is a factor, and R automatically constructs the dummy
> variables. Very nice.
>
> I need to then go on to do some other ML estimation using the same
> design matrix that's used for the OLS. I could, of course, do this
> manually. But it seems that lm() has done all this hard work. I wonder
> if there's a way to ask him nicely so as to get it. :-)
model.matrix()
> f <- factor(sample(1:10, 100, replace = TRUE))
> x <- rnorm(100)
> y <- rnorm(100)
> m <- lm(y ~ x + f)
> model.matrix(m)
(Intercept) x f2 f3 f4 f5 f6 f7 f8 f9 f10
1 1 1.8256930313 0 0 0 0 0 1 0 0 0
2 1 0.5129526275 0 0 0 1 0 0 0 0 0
3 1 0.6791212194 0 0 1 0 0 0 0 0 0
4 1 2.4711715848 0 0 0 0 0 0 1 0 0
5 1 0.5646964940 0 1 0 0 0 0 0 0 0
6 1 0.2640087965 0 0 0 0 1 0 0 0 0
###<snip />
You can also do this directly without the lm step:
model.matrix(y ~ x + f)
HTH
G
--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Gavin Simpson [t] +44 (0)20 7679 0522
ECRC, UCL Geography, [f] +44 (0)20 7679 0565
Pearson Building, [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street, London [w] http://www.ucl.ac.uk/~ucfagls/
UK. WC1E 6BT. [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
More information about the R-help
mailing list