简体   繁体   中英

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

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?

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 eg

(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM