如何从包含多个 lm() 的 lm() 对象导出系数?
How do I export coefficients from a lm() object containing multiple lm()?
我有一个对象 (S3; lm),其中包含 471 个不同模型的线性回归输出。我正在尝试提取每个模型中特定变量的标准误差,但我不确定该怎么做,有人可以帮忙吗?具体来说,我想为保存在“fit”对象中的 471 个模型中的每个模型提取变量“p”的标准误差。
varnames = names(merged1)[2036:2507]
fit <- lapply(varnames,
FUN=function(p) lm(formula(paste("Dx ~ x + y + z + q +", p)),data=merged1))
names(fit) <- varnames
非常感谢!
备注
编辑以反映匿名函数 p,而不是 x,如前所述。
sapply(fit,function(x) summary(x)$coefficients[p,][2],simplify = F)
子集到第二个元素为变量提供标准错误。
使用最后注释中可重复显示的拟合调用 map_dfr
和 tidy
,这将给出包含系数和相关统计数据的数据框。我们过滤掉我们想要的行。
library(broom) # tidy
library(dplyr)
library(purrr) # map_dfr
fit %>%
map_dfr(tidy, .id = "variable") %>%
filter(term == variable)
给予:
# A tibble: 8 x 6
variable term estimate std.error statistic p.value
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 hp hp -0.0147 0.0147 -1.00 0.325
2 drat drat 1.21 1.50 0.812 0.424
3 wt wt -3.64 1.04 -3.50 0.00160
4 qsec qsec -0.243 0.402 -0.604 0.551
5 vs vs -0.634 1.90 -0.334 0.741
6 am am 1.93 1.34 1.44 0.161
7 gear gear 0.158 0.910 0.174 0.863
8 carb carb -0.737 0.393 -1.88 0.0711
备注
我们使用 R 中内置的 mtcars 可重复地计算拟合度。
data <- mtcars
resp <- "mpg" # response
fixed <- c("cyl", "disp") # always include these
varnames <- setdiff(names(data), c(resp, fixed)) # incl one at a time
fit <- Map(function(v) {
fo <- reformulate(c(fixed, v), resp)
lm(fo, data)
}, varnames)
已更新
重大修订。
我有一个对象 (S3; lm),其中包含 471 个不同模型的线性回归输出。我正在尝试提取每个模型中特定变量的标准误差,但我不确定该怎么做,有人可以帮忙吗?具体来说,我想为保存在“fit”对象中的 471 个模型中的每个模型提取变量“p”的标准误差。
varnames = names(merged1)[2036:2507]
fit <- lapply(varnames,
FUN=function(p) lm(formula(paste("Dx ~ x + y + z + q +", p)),data=merged1))
names(fit) <- varnames
非常感谢!
备注 编辑以反映匿名函数 p,而不是 x,如前所述。
sapply(fit,function(x) summary(x)$coefficients[p,][2],simplify = F)
子集到第二个元素为变量提供标准错误。
使用最后注释中可重复显示的拟合调用 map_dfr
和 tidy
,这将给出包含系数和相关统计数据的数据框。我们过滤掉我们想要的行。
library(broom) # tidy
library(dplyr)
library(purrr) # map_dfr
fit %>%
map_dfr(tidy, .id = "variable") %>%
filter(term == variable)
给予:
# A tibble: 8 x 6
variable term estimate std.error statistic p.value
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 hp hp -0.0147 0.0147 -1.00 0.325
2 drat drat 1.21 1.50 0.812 0.424
3 wt wt -3.64 1.04 -3.50 0.00160
4 qsec qsec -0.243 0.402 -0.604 0.551
5 vs vs -0.634 1.90 -0.334 0.741
6 am am 1.93 1.34 1.44 0.161
7 gear gear 0.158 0.910 0.174 0.863
8 carb carb -0.737 0.393 -1.88 0.0711
备注
我们使用 R 中内置的 mtcars 可重复地计算拟合度。
data <- mtcars
resp <- "mpg" # response
fixed <- c("cyl", "disp") # always include these
varnames <- setdiff(names(data), c(resp, fixed)) # incl one at a time
fit <- Map(function(v) {
fo <- reformulate(c(fixed, v), resp)
lm(fo, data)
}, varnames)
已更新
重大修订。