R语言 如何使用多个因变量进行回归并比较这些模型?

e37o9pze  于 2023-05-11  发布在  其他
关注(0)|答案(2)|浏览(163)

下面,我设法运行多个因变量的回归。我如何将这些估计的结果分配给循环内的模型对象,然后使用例如rcompanion::compareLM()基于AIC/BIC度量比较这些模型?

depvar <- c("qsec", "hp")
indepvar <- paste(c("mpg", "wt", "am", "disp"), collapse = " + ")

for(i in 1:length(depvar)){
  est_model <- lm(paste(depvar[i],"~", indepvar), data=mtcars)
  res <- summary(est_model)
  print(list(depvar[i], res))
}
r8uurelv

r8uurelv1#

models <- list()
for(i in 1:length(depvar)){
  est_model <- lm(paste(depvar[i],"~", indepvar), data=mtcars)
  models[[i]] <- est_model
}

names(models) <- depvar
sapply(models, AIC)
#     qsec        hp 
# 97.38901 323.30591 

library(purrr)
library(broom)
map_dfr(models, glance, .id = "depvar")
# # A tibble: 2 × 13
#   depvar r.squared adj.r.sq…¹ sigma stati…² p.value    df logLik   AIC   BIC devia…³ df.re…⁴  nobs
#   <chr>      <dbl>      <dbl> <dbl>   <dbl>   <dbl> <dbl>  <dbl> <dbl> <dbl>   <dbl>   <int> <int>
# 1 qsec       0.727      0.687  1.00    18.0 2.63e-7     4  -42.7  97.4  106.    27.0      27    32
# 2 hp         0.784      0.752 34.1     24.5 1.19e-8     4 -156.  323.   332. 31450.       27    32
# # … with abbreviated variable names ¹​adj.r.squared, ²​statistic, ³​deviance, ⁴​df.residual

不过我应该警告一下,AICBIC并不适合比较具有不同响应的模型。

hkmswyz6

hkmswyz62#

对于broom,你可以这样做:

library(broom)
library(purrr)

depvar <- c("qsec", "hp")
indepvar <- paste(c("mpg", "wt", "am", "disp"), collapse = " + ")

depvar |> 
  purrr::set_names() |>
  purrr::map(\(dep) lm(paste(dep,"~", indepvar), data=mtcars) |> broom::glance()) |> 
  list_rbind(names_to = "depvar")
#> # A tibble: 2 × 13
#>   depvar r.squared adj.r.squared sigma statistic      p.value    df logLik   AIC
#>   <chr>      <dbl>         <dbl> <dbl>     <dbl>        <dbl> <dbl>  <dbl> <dbl>
#> 1 qsec       0.727         0.687  1.00      18.0 0.000000263      4  -42.7  97.4
#> 2 hp         0.784         0.752 34.1       24.5 0.0000000119     4 -156.  323. 
#> # ℹ 4 more variables: BIC <dbl>, deviance <dbl>, df.residual <int>, nobs <int>

创建于2023-05-09,使用reprex v2.0.2

相关问题