[R] Extracting formula from an lm object

Berwin A Turlach berwin at maths.uwa.edu.au
Sun Aug 24 10:09:54 CEST 2008


G'day Murray,

On Sun, 24 Aug 2008 18:34:39 +1200
Murray Jorgensen <maj at stats.waikato.ac.nz> wrote:

> I want to extra the part of the formula not including the response
> variable from an lm object. For example if the lm object ABx.lm was
> created by the call
> 
> ABx.lm <- lm( y ~ A + B + x, ...)
> 
> Then ACx.lm is saved as part of a workspace.
> I wish to extract   "~ A + B + x".  Later in my code I will fit
> another linear model of the form z ~ A + B + x for some other
> response variable z. I would be grateful for any suggestions of a
> nice way to do this.

AFAIK, a formula is essentially a list of two or three components.  The
first component is "~".  The second is the LHS of the formula if there
are three components; otherwise the RHS of the formula.  The third
component, if it exists, is the RHS of the formula.

So storing "~ A + B + x" and manipulating this part for different
responses could turn out to be painful; you would have to insert the
new LHS as the second component of the list.  I would suggest that it
is easier to store the complete formula and just manipulate the LHS;
see:

R> library(MASS)
R> fm <- lm(time~dist+climb, hills)
R> formula(fm)
time ~ dist + climb
R> formula(fm)[[1]]
`~`
R> formula(fm)[[2]]
time
R> formula(fm)[[3]]
dist + climb
R> tt <- formula(fm)
R> tt[[2]] <- NULL
R> tt
~dist + climb

R> tt <- formula(fm)
R> class(tt[[2]])
[1] "name"
R> typeof(tt[[2]])
[1] "symbol"
R> tt[[2]] <- as.name("y")
R> tt
y ~ dist + climb

R> tt <- formula(fm)
R> tt[[2]] <- as.symbol("z")
R> tt
z ~ dist + climb

HTH.

Cheers,

	Berwin

=========================== Full address =============================
Berwin A Turlach                            Tel.: +65 6515 4416 (secr)
Dept of Statistics and Applied Probability        +65 6515 6650 (self)
Faculty of Science                          FAX : +65 6872 3919       
National University of Singapore
6 Science Drive 2, Blk S16, Level 7          e-mail: statba at nus.edu.sg
Singapore 117546                    http://www.stat.nus.edu.sg/~statba



More information about the R-help mailing list