通过单个模型为从循环中提取的多次迭代创建摘要

Create summary for multiple iterations extracted from loop via single model

我创建了一个函数,它是 运行 lm 回归的多次迭代,使用不同的列作为循环中的因变量。我正在提取每次迭代的摘要和相关图,但我无法创建所有迭代结果的单个摘要 table。 由于我只有8列,所以我认为可以做到。 这是我的函数,数据如下

quantmodel<-function(a){
  i<-1
  a <- janitor::clean_names(a)
  colnames1 <- colnames(a)
  lm_model <- linear_reg() %>% 
    set_engine('lm') %>%
    set_mode('regression')
  
  out_lst <- vector('list', ncol(a))
  
  for (i in seq_along(a)) {
    lm_fit <- lm_model %>% 
      fit(as.formula(paste(colnames1[i], "~ .")), data = a)
    
    #Saving relevance plot of each parameter
    temp_plot = vip(lm_fit ,geom = "col", aesthetics = list(color = "black", fill = "black"))
    ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
    #Saving pdf of individual summaries
    pdf(paste0("summary_", colnames1[i],".pdf"), width = 10,height = 3) 
    grid.table(coef(summary(lm_fit$fit)))
    dev.off()
    paste0("m",i)<-lm_fit$fit
  }
  
}

quantmodel(set1)

数据: Set1(前 3 列)

Imp of family Imp of friends Imp of Leisure
2 1 1
1 2 1

由于您没有提供 MINIMAL WORKING EXAMPLE,我们无法正确诊断您的问题。

就是说,一种选择是确保您的函数 returns 模型列表,然后将其提供给 modelsummary function. 在这个示例代码中,请注意 return()最后调用 modelsummary() 调用:

quantmodel<-function(a){
  i<-1
  a <- janitor::clean_names(a)
  colnames1 <- colnames(a)
  lm_model <- linear_reg() %>% 
    set_engine('lm') %>%
    set_mode('regression')
  
  out_lst <- list()
  
  for (i in seq_along(a)) {
    lm_fit <- lm_model %>% 
      fit(as.formula(paste(colnames1[i], "~ .")), data = a)

    out_lst[[i]] <- lm_fit
    
    #Saving relevance plot of each parameter
    temp_plot = vip(lm_fit ,geom = "col", aesthetics = list(color = "black", fill = "black"))
    ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
    #Saving pdf of individual summaries
    pdf(paste0("summary_", colnames1[i],".pdf"), width = 10,height = 3) 
    grid.table(coef(summary(lm_fit$fit)))
    dev.off()
    paste0("m",i)<-lm_fit$fit
  }

  return(out_lst)
  
}

library(modelsummary)
models <- quantmodel(set1)
modelsummary(dvnames(models))