Hein
Hein

Reputation: 175

recursively write out model matrix in R

in the analysis I am running there are many predictor variables fro which I would like to build a model matrix. However, the model matrix requires a formula in a format such as

t<-model.matrix(f[,1]~f[,2]+f[,3]+....)

if my data frame is called f is there a quick way with paste or somethign just to write out this formula recusively? Otherwise Iw oudl need to type everything

Upvotes: 1

Views: 58

Answers (1)

IRTFM
IRTFM

Reputation: 263451

Why not use:

f <- data.frame(z = 1:10, b= 1:10, d=factor(1:10))

 model.matrix(~. , data=f[-1])
#-------------
   (Intercept)  b d2 d3 d4 d5 d6 d7 d8 d9 d10
1            1  1  0  0  0  0  0  0  0  0   0
2            1  2  1  0  0  0  0  0  0  0   0
3            1  3  0  1  0  0  0  0  0  0   0
4            1  4  0  0  1  0  0  0  0  0   0
5            1  5  0  0  0  1  0  0  0  0   0
6            1  6  0  0  0  0  1  0  0  0   0
7            1  7  0  0  0  0  0  1  0  0   0
8            1  8  0  0  0  0  0  0  1  0   0
9            1  9  0  0  0  0  0  0  0  1   0
10           1 10  0  0  0  0  0  0  0  0   1
attr(,"assign")
 [1] 0 1 2 2 2 2 2 2 2 2 2
attr(,"contrasts")
attr(,"contrasts")$d
[1] "contr.treatment"

Compare to what you get with:

> model.matrix(z~., f)
   (Intercept)  b d2 d3 d4 d5 d6 d7 d8 d9 d10
1            1  1  0  0  0  0  0  0  0  0   0
2            1  2  1  0  0  0  0  0  0  0   0
3            1  3  0  1  0  0  0  0  0  0   0
4            1  4  0  0  1  0  0  0  0  0   0
5            1  5  0  0  0  1  0  0  0  0   0
6            1  6  0  0  0  0  1  0  0  0   0
7            1  7  0  0  0  0  0  1  0  0   0
8            1  8  0  0  0  0  0  0  1  0   0
9            1  9  0  0  0  0  0  0  0  1   0
10           1 10  0  0  0  0  0  0  0  0   1
attr(,"assign")
 [1] 0 1 2 2 2 2 2 2 2 2 2
attr(,"contrasts")
attr(,"contrasts")$d
[1] "contr.treatment"

Upvotes: 0

Related Questions