我为这个愚蠢的问题道歉...但我似乎找不到简单的解决办法

我想从拟合线性模型中提取标准化系数(在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,]

R相关问答推荐

从R中的另一个包扩展S3类的正确方法是什么

R for循环返回到先前值

par函数中的缩写,比如mgp,mar,mai是如何被破译的?

如何从像glm这样的模型中提取系数表的相关性?

从外部文件读取多个值作为字符向量

矩阵的堆叠条形图,条形图上有数字作为标签

在RStudio中堆叠条形图和折线图

plotly hover文本/工具提示在shiny 中不起作用

如何根据数据帧中的值从该数据帧中提取值?

R中有约束的优化问题:如何用复数和对数效益函数解决问题?

条形图顶部与其错误条形图不对齐

自动STAT_SUMMARY统计与手动标准误差之间的差异

TidyVerse中长度不等的列结合向量

在鼠标悬停时使用Plotly更改geom_point大小

根据排名的顶点属性调整曲线图布局(&Q)

把代码写成dplyr中的group_by/摘要更简洁吗?

如何在分组蜂群小区中正确定位标签

在shiny /bslb中,当卡片是从json生成时,如何水平排列卡片?

如何将数据框压缩为更宽,同时将行输入保持为行输入,而不是R中的列名?

使用离散标签自定义图例,用于具有连续但已入库的数据的热图