我为这个愚蠢的问题道歉...但我似乎找不到简单的解决办法
我想从拟合线性模型中提取标准化系数(在R中)
编辑(以下是一些 comments ):
对于那些认为我问了一个愚蠢的问题的人,我深表歉意,对于那些花时间回答这个问题的人,我深表感谢.
我为这个愚蠢的问题道歉...但我似乎找不到简单的解决办法
我想从拟合线性模型中提取标准化系数(在R中)
编辑(以下是一些 comments ):
对于那些认为我问了一个愚蠢的问题的人,我深表歉意,对于那些花时间回答这个问题的人,我深表感谢.
在QuantPsyc
包中有一个方便的函数,叫做lm.beta
.然而,我认为最简单的方法就是将变量标准化.然后,系数将自动成为标准化的"β"系数(即标准偏差系数).
例如,
lm(scale(your.y) ~ scale(your.x), data=your.Data)
将给出标准化系数.
Are they really the same?以下说明两者是相同的:
library("QuantPsyc")
mod <- lm(weight ~ height, data=women)
coef_lmbeta <- lm.beta(mod)
coef_lmbeta
> height
0.9955
mod2 <- lm(scale(weight) ~ scale(height), data=women)
coef_scale <- coef(mod2)[2]
coef_scale
> scale(height)
0.9955
all.equal(coef_lmbeta, coef_scale, check.attributes=F)
[1] TRUE
这表明两者应该是一样的.
How to avoid clumsy variable names?
In case you don't want to deal with these clumsy variable names such as scale(height)
, one option is to standardize the variables outside the lm
call in the dataset itself. 例如,
women2 <- lapply(women, scale) # standardizes all variables
mod3 <- lm(weight ~ height, data=women2)
coef_alt <- coef(mod3)[2]
coef_alt
> height
0.9955
all.equal(coef_lmbeta, coef_alt)
[1] TRUE
How do I standardize multiple variables conveniently? In the likely event that you don't want to standardize all variables in your dataset, you could pick out all that occur in your formula. 例如, referring to the mtcars
-dataset now (since women
only contains height
and weight
):
假设以下是我想要估计的回归模型:
modelformula <- mpg ~ cyl + disp + hp + drat + qsec
我们可以利用all.vars
给我一个变量名向量的事实.
all.vars(modelformula)
[1] "mpg" "cyl" "disp" "hp" "drat" "qsec"
We can use this to subset the dataset accordingly. 例如,
mycars <- lapply(mtcars[, all.vars(modelformula)], scale)
将给我一个所有变量都已标准化的数据集.使用mycars
的线性回归现在将给出标准化的beta.不过,请确保标准化所有这些变量是有意义的!
Potential issue with only one variable:如果您的模型公式只包含一个解释变量,并且您正在使用内置数据帧(而不是tibbles),则建议进行以下调整(注释中的积分到@JerryT):
mycars <- lapply(mtcars[, all.vars(modelformula), drop=F], scale)
这是因为当从标准数据帧中只提取一列时,R会重新生成一个向量,而不是数据帧.drop=F
将防止这种情况发生.如果使用例如tibbles
,这也不会成为问题.见例句.
class(mtcars[, "mpg"])
[1] "numeric"
class(mtcars[, "mpg", drop=F])
[1] "data.frame"
library(tidyverse)
class(as.tibble(mtcars)[, "mpg"])
[1] "tbl_df" "tbl" "data.frame"
数据帧中的Another issue with missing values(在注释中再次计入@JerryT):默认情况下,R的lm
将删除至少缺少一列的所有rows.另一方面,scale
将获取所有未缺失的值,即使观测值在另一列中有缺失值.如果要模仿lm
的动作,可能需要先删除所有缺少值的行,如下所示:
all_complete <- complete.cases(df)
df[all_complete,]