Skip to content

Instantly share code, notes, and snippets.

@wch
Created January 23, 2023 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/5f46b51775ea361610c1d592174e8e62 to your computer and use it in GitHub Desktop.
Save wch/5f46b51775ea361610c1d592174e8e62 to your computer and use it in GitHub Desktop.
`stats::update()` weirdness
# Example 1: running at top level. This works.
model_str1 <- "speed~dist"
model1 <- lm(formula=model_str1, data=cars)
stats::update(model1, y = TRUE)
#>
#> Call:
#> lm(formula = model_str1, data = cars, y = TRUE)
#>
#> Coefficients:
#> (Intercept) dist
#> 8.2839 0.1656
# Example 2: model is created in a function, then update() is called at the top
# level. This throws an error.
mymodel <- function() {
model_str <- "speed~dist"
model <- lm(formula=model_str, data=cars)
}
update(mymodel(), y = TRUE)
#> Error in stats::model.frame(formula = model_str, data = cars, drop.unused.levels = TRUE): object 'model_str' not found
# Example 3: Same as example 2, but there is a variable with the same name as
# one inside of mymodel(), and it causes incorrect result.
model_str <- "dist~speed"
update(mymodel(), y = TRUE) # <- This generates the wrong result!!
#>
#> Call:
#> lm(formula = model_str, data = cars, y = TRUE)
#>
#> Coefficients:
#> (Intercept) speed
#> -17.579 3.932
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment