Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to determine if a model formula only has an intercept

In R formula syntax, occasionally a user will specify a very simple model that only has an intercept, e.g.

fit = lm(Response ~ 1, data)

These models allow for simplification relative to more complex models, e.g. lm(Response ~ A + B + A:B, ...) and I would like to have an easy way to detect when the RHS of the equation only contains a 1 and no other terms. Text manipulations seem possible, but are there any other ways to do this using the R formula class or other methods?

like image 815
evolvedmicrobe Avatar asked Dec 08 '22 20:12

evolvedmicrobe


1 Answers

The most straightforward way is

names(coef(fit))

If this only shows "(Intercept)", then you know.


Another way is to check "terms" object. In fact, this is lm independent. You create a formula:

f <- Response ~ 1

then terms(f) creates "terms" object. Later, lmObject inherits this.

Check out

attr(terms(fit), "intercept")
## to use formula only without actually fitting a model, do
## attr(terms(f), "intercept")

If this is 1, then you have intercept; if 0, you don't have it.

Now, check out

length(attr(terms(fit), "term.labels"))
## to use formula only without actually fitting a model, do
## attr(terms(f), "terms.labels")

If bigger than 0, you have other covariates; if 0, bingo.

like image 198
Zheyuan Li Avatar answered Dec 28 '22 08:12

Zheyuan Li