Jared - 10 months ago 63

R Question

I have a

`data.frame`

`testFrame <- data.frame(First=sample(1:10, 20, replace=T),`

Second=sample(1:20, 20, replace=T), Third=sample(1:10, 20, replace=T),

Fourth=rep(c("Alice","Bob","Charlie","David"), 5),

Fifth=rep(c("Edward","Frank","Georgia","Hank","Isaac"),4))

I want to build out a

`matrix`

`model.matrix(~ First + Second + Third + Fourth + Fifth, data=testFrame)`

As expected when running

`lm`

`matrix`

`glmnet`

Is there a way to have

`model.matrix`

Answer

You need to reset the `contrasts`

for the factor variables:

```
model.matrix(~ Fourth + Fifth, data=testFrame,
contrasts.arg=list(Fourth=contrasts(testFrame$Fourth, contrasts=F),
Fifth=contrasts(testFrame$Fifth, contrasts=F)))
```

or, with a little less typing and without the proper names:

```
model.matrix(~ Fourth + Fifth, data=testFrame,
contrasts.arg=list(Fourth=diag(nlevels(testFrame$Fourth)),
Fifth=diag(nlevels(testFrame$Fifth))))
```

Source (Stackoverflow)