How to reliably get dependent variable name from formula object?

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

    I know this question is quite old, but I thought I'd add a base R answer which doesn't require indexing, doesn't depend on the order of the variables listed in a call to all.vars, and which gives the response variables as separate elements when there is more than one:

    myformula <- formula("depVar1 + depVar2 ~ Var1 + Var2")
    all_vars <- all.vars(myformula)
    response <- all_vars[!(all_vars %in% labels(terms(myformula)))]
    
    > response
    [1] "depVar1" "depVar2"
    

提交回复
热议问题