[英]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):
3.6.2,我得到这个代码(执行线性回归):
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.我的理解是
lm.fit
是线性模型的基本拟合函数。 Why would I overwrite it with the result of lm()
?为什么我要用
lm()
的结果覆盖它? Then lm.fit
stops being a function and becomes a list.然后
lm.fit
不再是一个函数,而是一个列表。 Shouldn't I just assign the result of lm()
to a new variable?我不应该将
lm()
的结果分配给一个新变量吗?
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.在这方面,
var1
、 lm2
等形式的变量名通常是安全的选择。 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 <-
). Hadley Wickham 的风格指南推荐
var_1
, lm_2
,尽管如果您在ESS中使用“智能下划线”(将_
更改为<-
),这些下划线可能会有点令人厌烦。
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.给出
NULL
,表明lm.fit
已经存在。
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
和函数lm.fit
仍然按预期工作,我们可以看到:
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:也就是说,
lm.fit
在调用时仍然是一个函数,因为它仍然定义在包stats
的命名空间中,如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.