4

I'm using model.frame() in R (to use within a function) but I can't manage to exclude some of the variables with the formula by using -. For example, in a data frame (data) with variables "y", "x1", "x2" and "x3", by using:

model.frame(y ~ . - x3, data)

I would get a data frame including all "y", "x1", "x2" and "x3".

Is there a way to exclude "x3" using a formula and not removing the variable directly as in:data[,-4]?

Kara
  • 6,115
  • 16
  • 50
  • 57
jcbslmn
  • 43
  • 3
  • Assume that you are not looking for y ~ x1 + x2 ? – PhilC Apr 26 '17 at 21:40
  • Relevant (though it doesn't answer this question) - http://stackoverflow.com/questions/5251507/how-to-succinctly-write-a-formula-with-many-variables-from-a-data-frame – thelatemail Apr 26 '17 at 23:03

1 Answers1

4

I can't figure out how to do this super cleanly, but you can do it in a couple of steps:

# example data
data <- data.frame(y=0,x1=1,x2=2,x3=3)

Get the full expanded formula in the context of data and then remove x3:

mf <- model.frame(y ~ ., data, subset=FALSE)
#formula(mf)
##y ~ x1 + x2 + x3
model.frame(update(formula(mf), ~ . -x3), data=data)
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • 2
    I'm not sure if this could be considered more "cleanly": `model.frame(formula(terms(y ~ . - x3, data = data, simplify = TRUE)), data)` – Roland Apr 27 '17 at 06:44