# [R] Removing terms from formula

Gabor Grothendieck ggrothendieck at gmail.com
Thu Nov 30 08:44:44 CET 2006

```One correction (to the get):

Do you really want the 1?  Normally the intercept is not explicitly
given unless there are no other terms in the formula so assuming you
only want it if you have otherwise removed all the variables then:

zap1 <- function(fo) {
L <- sapply(all.vars(fo[[length(fo)]]), function(x)
nlevels(get(x, environment(fo))), simplify = FALSE)
fo <- eval.parent(do.call(substitute, list(fo, L[c(L) == 1])))
update(fo, . ~ .)
}

# test data
x <- y <- 1:3
z <- factor(0*x)
fo <- x ~ y + z

# test
zap1(fo) # x ~ y
y <- z
zap1(fo) # x ~ 1

On 11/30/06, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> Do you really want the 1?  Normally the intercept is not explicitly
> given unless there are no other terms in the formula so assuming you
> only want it if you have otherwise removed all the variables then:
>
> zap1 <- function(fo) {
>   L <- sapply(all.vars(fo[[length(fo)]]), function(x)
>      nlevels(get(x)), simplify = FALSE)
>   fo <- eval.parent(do.call(substitute, list(fo, L[c(L) == 1])))
>   update(fo, . ~ .)
> }
>
> # test data
> x <- y <- 1:3
> z <- factor(0*x)
> fo <- x ~ y + z
>
> # test
> zap1(fo) # x ~ y
> y <- z
> zap1(fo) # x ~ 1
>
> On 11/29/06, McGehee, Robert <Robert.McGehee at geodecapital.com> wrote:
> > R-help,
> > Given a simple linear model, say lm(x ~ y + z), I would like to remove
> > model terms that are factors with only one level. Thus, if 'z' were a
> > factor with only one level, lm(x ~ y + z) becomes lm(x ~ y + 1).
> > Likewise, if both 'y' and 'z' are one-level factors, then the resulting
> > calculation is simply lm(x ~ 1).
> >
> > Unfortunately, I have not been able to come up with an elegant solution
> > to this. Any suggestions would be greatly appreciated.
> >
> > Thanks,
> > Robert
> >
> > Robert McGehee, CFA
> > Quantitative Analyst
> > Geode Capital Management, LLC
> > One Post Office Square, 28th Floor | Boston, MA | 02109
> > Tel: 617/392-8396    Fax:617/476-6389
> > mailto:robert.mcgehee at geodecapital.com
> >
> >
> >
> > This e-mail, and any attachments hereto, are intended for us...{{dropped}}
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help