Excluding variables when extracting model frame from formula in R

I am using model.frame()

in R (for use inside a function), but I cannot exclude some of the variables with a formula using -

. For example, in a data (data) frame with variables "y", "x1", "x2" and "x3" 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" with a formula and not delete the variable directly like in data[,-4]

:?

+3


source to share


1 answer


I can't figure out how to make it super clean, 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 complete expanded formula in context 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)

      

+4


source







All Articles