How to reliably get dependent variable name from formula object?

前端 未结 7 856
清酒与你
清酒与你 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:20

    I suppose you could also cook your own function to work with terms():

    getResponse <- function(formula) {
        tt <- terms(formula)
        vars <- as.character(attr(tt, "variables"))[-1] ## [1] is the list call
        response <- attr(tt, "response") # index of response var
        vars[response] 
    }
    
    R> myformula <- formula("depVar ~ Var1 + Var2")
    R> getResponse(myformula)
    [1] "depVar"
    

    It is just as hacky as as.character(myformyula)[[2]] but you have the assurance that you get the correct variable as the ordering of the call parse tree isn't going to change any time soon.

    This isn't so good with multiple dependent variables:

    R> myformula <- formula("depVar1 + depVar2 ~ Var1 + Var2")
    R> getResponse(myformula)
    [1] "depVar1 + depVar2"
    

    as they'll need further processing.

提交回复
热议问题