# [R] Follow Up To: Splitting the left and right hand terms of a formula

Vincent Goulet vincent.goulet at act.ulaval.ca
Tue Jul 25 22:26:37 CEST 2006

```Le Mardi 25 Juillet 2006 15:48, Daniel Gerlanc a écrit :
> Hi All,
>
> I sent the following message to R-help on July 14th, 2006:
>
> Let's say I have the following formula:
>
> a.formula <- x ~ y + z
>
> I want to extract the left and right-hand sides of the function so
> that I have two character vectors like the ones you would create using
> the following assignments:
>
> left.hand.side <- "x"
> right.hand.side <- c("y", "z")
>
> One way to do this follows:
>
> left.hand.side <- unlist(dimnames(attr(terms(a.formula), "factors"))[1])
> right.hand.side <- unlist(dimnames(attr(terms(a.formula), "factors"))[-1])
>
> Is there a better or cleaner way to do this?
>
> I got one reply to try this (thanks Gabor!):
> > all.vars(update(a.formula, .~0))
>
> [1] "x"
>
> > all.vars(update(a.formula, 0~.))
>
> [1] "y" "z"
>
> This works, but seems a bit of a hack.
>
> There are two methods, "getCovariateFormula", and "getCovariate,"
> which return, respectively, objects of class "formula" for the left
> and right hand sides of the formula.  To get the right hand side or
> left hand side I wrap one of these method calls in a call to
> "all.vars".  Is there a better way to get the left or right hand side
> of the formula, or is this it?

> f <- x ~ y + z
> class(f)
[1] "formula"
> str(f)
Class 'formula' length 3 x ~ y + z
..- attr(*, ".Environment")=length 56 <environment>
> f[[1]]
`~`
> f[[2]]
x
> f[[3]]
y + z
> all.vars(f[[2]])
[1] "x"
> all.vars(f[[3]])
[1] "y" "z"

If needed, the vertical bar | is also recognized as a separation symbol:

> f <- ~ x | y + z
> f[[2]]
x | y + z
> f[[2]][[2]]
x
> f[[2]][[3]]
y + z

Bye!    Vincent

--
Vincent Goulet, Associate Professor
École d'actuariat
Université Laval, Québec
Vincent.Goulet at act.ulaval.ca   http://vgoulet.act.ulaval.ca

```