简体   繁体   中英

How to remove intercept from formula

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM