如何拟合多个模型并将嵌套列表中的模型输出提取到 df 中

How to fit multiple models and extract model outputs from a nested list into a df

我有一个包含许多 Y 和 X 变量的数据框。我想通过遍历所有 X 和 Y 变量来用 lm() 拟合多个单一线性模型。我正在努力将其他 Y 变量包括在内,但我正在努力迭代 X 变量。

我的数据看起来像这样:

set.seed(200)
df <- data.frame(y1 = c(rnorm(n=20, mean = 5)),
                 y2 = c(rnorm(n=20, mean = 5)),
                 x1 = c(rnorm(n=20, mean = 13)), 
                 x2 = c(rnorm(n=20, mean = 14)), 
                 x3 = c(rnorm(n=20, mean = 15)))

我尝试了多种拟合这些模型的方法,但最好的方法似乎是使用 for 循环。

models <- list() #creating an empty list
for (i in names(df)[3:5]){ #choosing just the x-variables from the df
      
    models[[i]]   <- lm(y1 ~ get(i), df)
}

我的输出在 models 列表中,我可以通过 summary(models[[1]] 访问我想要的统计数据,但我不想为每个适合的模型都这样做。有没有办法使用 do.callmap_df 或其他方法提取我想要的统计信息?具体来说,我想要 r.squaredresidual standard errorp-valuef.statistic

此示例基于 Wickham 和 Grolemund 的“R for Data Science”的第 25 章。阅读它以获得解释。

library(dplyr)
library(modelr)
library(tidyverse)

set.seed(200)
df <- data.frame(y1 = c(rnorm(n=20, mean = 5)),
                 y2 = c(rnorm(n=20, mean = 5)),
                 x1 = c(rnorm(n=20, mean = 13)), 
                 x2 = c(rnorm(n=20, mean = 14)), 
                 x3 = c(rnorm(n=20, mean = 15)))

#Set up your data so that you nest each set of variables as dataframe within a dataframe
dfy <- df %>% select(starts_with("y"))
dfx <- df %>% select(starts_with("x"))

dat_all <- data.frame()

for (y in names(dfy)){
    for(x in names(dfx)){
        r <- paste(x,"_",y)
        data = (data.frame(x = dfx[x], y = dfy[y]))
        names(data) <- c("x", "y")
        dd <- data.frame(vars = r, data = data) %>%
                group_by(vars) %>%
                nest()
        dat_all <- rbind(dat_all, dd)
    }
}

myModel <- function(df) {
    lm(data.x ~ data.y, data = df)
}


dat_all <- dat_all %>%
    mutate(model = map(data, myModel))


glance <- dat_all %>% 
    mutate(glance = map(model, broom::glance)) %>% 
    unnest(glance, .drop = TRUE)



glance %>%
    select(r.squared, p.value)


#vars    r.squared p.value
#<chr>       <dbl>   <dbl>
#1 x1 _ y1 0.00946     0.683
#2 x2 _ y1 0.00474     0.773
#3 x3 _ y1 0.00442     0.781
#4 x1 _ y2 0.106       0.162
#5 x2 _ y2 0.0890      0.201
#6 x3 _ y2 0.0000162   0.987