WAF WAF - 2 months ago 7
R Question

Get the right hand side variables of an R formula

I'm writing my first S3 class and associated methods and I would like to know how to subset my input data set in order to keep only the variables specified in the formula?

data(iris)
f <- Species~Petal.Length + Petal.Width


With
model.frame(f,iris)
I get a subset with all the variables in the formula. How to automatically keep only the right hand side variables (in the example
Petal.Length
and
Petal.Width
)?

Answer

You want labels and terms; see ?labels, ?terms, and ?terms.object.

labels(terms(f))
# [1] "Petal.Length" "Petal.Width" 

In particular, labels.terms returns the "term.labels" attribute of a terms object, which excludes the LHS variable.