Remove variable wrapped in function from model formula in R

A terms-object is a formula with additional attributes:

update(mod, formula=drop.terms(mod$terms, 2, keep.response=TRUE)  )

Call:
lm(formula = y ~ scale(x1), data = data)

Coefficients:
(Intercept)    scale(x1)  
     5.0121       0.1236  

If you need to calculate that position from a string argument, then you can grep the term.labels attribute:

> grep( "x2", attr( mod$terms, "term.labels") )
[1] 2

Notice that this also succeeds with the interaction formula:

update(mod, formula=drop.terms(mod$terms, grep( "x2", attr( mod$terms, "term.labels") ), keep.response=TRUE) )
#----------

Call:
lm(formula = y ~ scale(x1), data = data)

Coefficients:
(Intercept)    scale(x1)  
     5.0121       0.1236  

Tags:

Regex

R