Let\'s say I have the following formula:
myformula<-formula(\"depVar ~ Var1 + Var2\")
How to reliably get dependent variable name from formu
Using all.vars
is very tricky as it won't detect the response from a one-sided formula. For example
all.vars(~x+1)
[1] "x"
that is wrong.
Here is the most reliable way of getting the response:
getResponseFromFormula = function(formula) {
if (attr(terms(as.formula(formula)) , which = 'response'))
all.vars(formula)[1]
else
NULL
}
getResponseFromFormula(~x+1)
NULL
getResponseFromFormula(y~x+1)
[1] "y"
Note that you can replace all.vars(formula)[1]
in the function with formula[2]
if the formula contains more than one variable for the response.