I have created a function which is running multiple iteration of lm regression using different columns as the dependent variable over a loop. I am extracting the summary of each iteration and the relavance graph, but I am not able to create a single summary table of all the iteration results. Since I have only 8 columns, I think it can be done. Here's my function with data below
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)
Data: Set1(first 3 columns)
Imp of family | Imp of friends | Imp of Leisure |
---|---|---|
2 | 1 | 1 |
1 | 2 | 1 |
CodePudding user response:
Since you do not provide a MINIMAL WORKING EXAMPLE, it is impossible for us to diagnose your problem correctly.
That said, one option would be to ensure that your function returns a list of models, and then feed that to the modelsummary
function. In this example code, note the return()
call at the end and the modelsummary()
call:
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))