Skip to content

proper work-flow with 'formula' objects and lm()

8 messages · Liviu Andronic, Duncan Murdoch, Brian Ripley +1 more

#
Dear all
I have a work-flow issue with lm(). When I use
Call:
lm(formula = y1 ~ x1, data = anscombe)

Coefficients:
(Intercept)           x1
     3.0001       0.5001


I get as expected the formula, "y1 ~ x1", in the print()ed results or
summary(). However, if I pass through a formula object
y1 ~ x1
Call:
lm(formula = form, data = anscombe)

Coefficients:
(Intercept)           x1
     3.0001       0.5001


then I only get the object name in the call, 'form', instead of the
formula. When passing a 'formula' object to lm, is it possible to
retain in the resulting 'lm' object the actual formula used for the
regression: "y1 ~ x1"?

Regards
Liviu
#
On 24/11/2011 2:48 PM, Liviu Andronic wrote:
It is retained.  terms(fit) will give it to you, if fit is an lm object.

Duncan Murdoch
#
On Thu, Nov 24, 2011 at 9:14 PM, Duncan Murdoch
<murdoch.duncan at gmail.com> wrote:
Thank you. The following works nicely.
y1 ~ x1
y1 ~ x1


However, I was hoping that there was a way to input the 'form' object
so that summary(x) would print the underlying formula used, not the
formula object name. I was thinking of something in the style of
x <- lm(deparse(form), anscombe)
summary(x)

Can this be done? Regards
Liviu
#
On Thu, 24 Nov 2011, Liviu Andronic wrote:

            
Yes.  That's a job for substitute (the second time today).
Call:
lm(formula = y1 ~ x1, data = anscombe)
...

  
    
#
On Thu, Nov 24, 2011 at 10:25 PM, Prof Brian Ripley
<ripley at stats.ox.ac.uk> wrote:
That's what I wanted. Thanks!

However, I do want to simplify the syntax and define a new function:
x.lm <-
  function(formula, data, ...)
{
  eval(substitute(lm(f, data, ...), list(f = formula)))
}

For the simple case it works just fine
y1 ~ x1
But it fails when I try to input more lm() arguments:
Error in eval(expr, envir, enclos) :
  ..1 used in an incorrect context, no ... to look in

Am I doing something obviously wrong? Regards
Liviu
#
On Thu, Nov 24, 2011 at 2:48 PM, Liviu Andronic <landronimirc at gmail.com> wrote:
Try this:
Call:
lm(formula = y1 ~ x1, data = anscombe)

Coefficients:
(Intercept)           x1
     3.0001       0.5001
#
You would get exactly the same problem with ...,, anway.

Here's a commonly used approach in R sources:

x.lm <- function(formula, data, ...)
{
     Call <- match.call(expand.dots = TRUE)
     Call[[1]] <- as.name("lm")
     Call$formula <- as.formula(terms(formula))
     eval(Call)
}
On Thu, 24 Nov 2011, Liviu Andronic wrote:

            

  
    
#
On Thu, Nov 24, 2011 at 11:55 PM, Prof Brian Ripley
<ripley at stats.ox.ac.uk> wrote:
I thank all those who came up with suggestions. Regards
Liviu