Majda Ammi - 10 months ago 84

R Question

I have a formula which I would like to use to create a model matrix, but for my use I need to stop the user from adding an intercept as this will be taken care of at a later stage in the regression. How can I remove the intercept from the formula and is there a better option than update?

Answer

You can do this a few ways. The first option specified below is probably the best way of going about this.

```
# Create dataset and form for example
dta <- data.frame(y = rnorm(3), x = rnorm(3), z = rnorm(3))
form <- y ~ x + z
# No censoring
(X <- model.matrix(form, dta))
# Option 1 (my default option)
tf <- terms(form)
attr(tf, "intercept") <- 0
model.matrix(tf, dta)
# Option 2
X[, !colnames(X) %in% "(Intercept)"]
# Option 3
form2 <- update(form, . ~ . - 1)
model.matrix(form2, dta)
```

Source (Stackoverflow)