Delete the response variable from a formula

Viewed 272

Is there a simple way to delete the response variable from a formula? I've tried using stats::update.formula, like this:

> update(y ~ x, ~ .)
y ~ x

But you can see that the above does not remove the response variable from the formula.

3 Answers

You can use NULL as the response.

update(y ~ x, NULL ~ .)
# ~x

If the formula has a LHS then that LHS is stored in the second component so:

fo <- y ~ x
fo[-2]
## ~x

Note that length(fo) can distinguish between formulas with and without a LHS.

length(fo)
## [1] 3
length(fo[-2])
## [1] 2

so if we don't know if there is a LHS and want to remove it if there is one then:

if (length(fo) == 3) fo[-2] else fo
## ~x

It's not terribly elegant, but you can do the following to delete the response variable:

formula(delete.response(terms(y ~ x)))
# ~x
Related