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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With