Why would I assign the result of lm() to lm.fit?

Viewed 44

From "An Introduction to Statistical Learning", Sec. 3.6.2, I get this code (to perform a linear regression):

library(MASS)
library(ISLR2)
lm.fit =lm(medv~lstat ,data=Boston )

My understanding is that lm.fit is the basic fitter function for linear models. Why would I overwrite it with the result of lm()? Then lm.fit stops being a function and becomes a list. Shouldn't I just assign the result of lm() to a new variable?

1 Answers

As suggested, posting as an answer.

It is best practice not to overwrite a variable which is already defined in the namespace of a loaded package, in order to avoid unwanted side-effects. Variable names of the form var1, lm2 etc. are typically safe choices in this regard. Hadley Wickham's Style Guide recommends var_1, lm_2, although personally those underscores can get a little tiresome if you are using the 'smart underscore' in ESS (changes _ to <-).

We can always check before assigning to a variable with e.g.

(if (!exists("lm.fit")) lm.fit  <- lm(medv ~ lstat, data=ISLR2::Boston))

which gives NULL, indicating that lm.fit already exists.

Assigning lm.fit is not a cardinal offense, as lm still works as expected as well as the function lm.fit, as we can see:

lm.fit  <- lm(medv ~ lstat, data=ISLR2::Boston)
lm(medv ~ lstat, data=ISLR2::Boston)
### Manually adding an intercept term below to get the same results
lm.fit(x=cbind(rep(1, length(Boston$lstat)), Boston$lstat),
   y=Boston$medv)$coefficients

That is, lm.fit is still found as a function when called as such as it remains defined in the namespace of the package stats, as shown by:

getAnywhere(lm.fit)

giving

2 differing objects matching ‘lm.fit’ were found
in the following places
  .GlobalEnv
  package:stats
  namespace:stats
Use [] to view one of them
Related