lm() inside a with() block

Quick and simple (to ask). I'm using the latest version of R an RStudio on my Mac.

The first lm() works, the second doesn't. The documentation for both functions is kind of spread out, so I can't trace a problem -- especially since R does not give me an error message. It quietly does whatever it's doing and the second fit isn't created.

theURL <- "http://lib.stat.cmu.edu/datasets/Andrews/T30.1"
theNames <- c("Table", "Number", "Row", "Experiment", "Temperature", "Concentration", "Time", "Unchanged", "Converted", "Unwanted")
Reaction <- read.table(theURL, header = F , col.names = theNames)
Reaction <- Reaction[-c(1:4)]

fitWorking <-lm(Converted~Temperature, data=Reaction)

with(Reaction, 
  fitBroken <- lm(Converted ~ Temperature)
)

Created on 2019-02-28 by the reprex package (v0.2.1)

For completeness, this is data table 30.1 from Andrews & Herzberg Data book.

You are leaving the output on a different environment (inside with statement) try this

theURL <- "http://lib.stat.cmu.edu/datasets/Andrews/T30.1"
theNames <- c("Table", "Number", "Row", "Experiment", "Temperature", "Concentration", "Time", "Unchanged", "Converted", "Unwanted")
Reaction <- read.table(theURL, header = F , col.names = theNames)
Reaction <- Reaction[-c(1:4)]
fitBroken <- with(Reaction, lm(Converted ~ Temperature))
fitBroken
#> 
#> Call:
#> lm(formula = Converted ~ Temperature)
#> 
#> Coefficients:
#> (Intercept)  Temperature  
#>      5.0731       0.3064

Created on 2019-03-01 by the reprex package (v0.2.1)

1 Like

You need to use <<- for the assignment to escape the "with" evaluation environment.

But I would say: in general consider not using with() with lm(). Organizing your code to use the data= argument is a good idea.

  
lm(mpg ~ cyl, data = mtcars)
#> 
#> Call:
#> lm(formula = mpg ~ cyl, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)          cyl  
#>      37.885       -2.876

with(mtcars, fit <<- lm(mpg ~ cyl))
fit
#> 
#> Call:
#> lm(formula = mpg ~ cyl)
#> 
#> Coefficients:
#> (Intercept)          cyl  
#>      37.885       -2.876

Created on 2019-02-28 by the reprex package (v0.2.1)

3 Likes

Drat! And I knew the answer, having written a warning to that effect one chapter ago.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.