Qaswed
Qaswed

Reputation: 3879

How to check formulas on inconsistency in R

In R I want to test a formula whether the user specified an intercept in his formula or not. Currently I'm using the function terms for this. In the following cases I get the desired output

terms(y ~ x)      #found an intercept
terms(y ~ 1 + x)  #found an intercept
terms(y ~ 0 + x)  #found no intercept
terms(y ~ -1 + x) #found no intercept

But in the cases the user gives an inconsistent input, I get (imo arbitrary)results from terms about the specification of an intercept.

terms(y ~ -1 + 1 + x) #found an intercept
terms(y ~ 1 - 1 + x)  #found no intercept
terms(y ~ 0 + 1 + x)  #found an intercept
terms(y ~ 1 + 0 + x)  #found no intercept

What I actually want is terms to throw an error or warning in these cases. Is this possible with terms, or do I have to do suchs checks on consistency "by hand" (via regular expressions etc.)?

Upvotes: 1

Views: 81

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269654

This will be 1 if formula fo has an intercept and 0 otherwise

has_intercept <- attr(terms(fo), "intercept")

so this will generate an error if there is an intercept:

if (has_intercept) stop("Intercept is not allowed")

Regarding the inconsistent remark in the question the way it works seems to be that it goes from left to right and uses the last one encountered so, for example, y ~ 0 + 1 + x has an intercept and y ~ 1 + 0 + x does not.

For consistency it is normally best to stick to R's rules rather than make up different rules of your own.

Upvotes: 1

Related Questions