Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete the response variable from a formula

Tags:

r

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.

like image 667
Cameron Bieganek Avatar asked Jan 07 '19 22:01

Cameron Bieganek


3 Answers

You can use NULL as the response.

update(y ~ x, NULL ~ .)
# ~x
like image 193
MrFlick Avatar answered Nov 15 '22 23:11

MrFlick


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
like image 29
G. Grothendieck Avatar answered Nov 15 '22 22:11

G. Grothendieck


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

formula(delete.response(terms(y ~ x)))
# ~x
like image 2
Cameron Bieganek Avatar answered Nov 15 '22 22:11

Cameron Bieganek