how do I get vector ("x", "z") from string "y ~ x + z"?

Viewed 46

I have a regression formula string "y ~ x + z". How do I get "x" and "z" from it? I need to get the column names I use for regression..

1 Answers

We can convert the string to formula object and get the variables with all.vars. The first element would be the dependent variable, so it is removed with indexing ([-1])

all.vars(as.formula(str1))[-1]
#[1] "x" "z"

Or as @ducymayr mentioned

attr(terms(as.formula(str1)), "term.labels")
#[1] "x" "z"

data

str1 <- "y ~ x + z"
Related