How to reliably get dependent variable name from formula object?

前端 未结 7 855
清酒与你
清酒与你 2021-01-31 02:29

Let\'s say I have the following formula:

myformula<-formula(\"depVar ~ Var1 + Var2\")

How to reliably get dependent variable name from formu

7条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 03:17

    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.

提交回复
热议问题