如何将回归模型列表中的各模型结果保存为独立文本文件?
First, let's fix a small critical issue in your initial code: your varlist should be a vector of character strings (the names of your variables) instead of the variables themselves. Otherwise, the substitute step won't work correctly, and we can't derive meaningful filenames later. Update that line to:
varlist <- c("var1", "var2", "var3")
Now, to save each model summary in mlist_summ to a separate text file with a unique filename (tied to the corresponding variable), you can use a for loop that iterates over both the summaries and variable names. Here are two common approaches:
1. Using stargazer (for formatted, publication-ready output)
If you prefer structured, clean output from stargazer, use the out parameter to specify the filename for each iteration:
# Load stargazer if not already installed/loaded # install.packages("stargazer") library(stargazer) # Loop through each model summary and variable name for (i in seq_along(mlist_summ)) { # Grab the current variable name current_var <- varlist[i] # Create a unique filename (e.g., "model_summary_var1.txt") filename <- paste0("model_summary_", current_var, ".txt") # Save the formatted summary to the file stargazer(mlist_summ[[i]], type = "text", out = filename) }
2. Using capture.output (for standard R print output)
If you want to save the default printed output of the lmer summary (no extra formatting), use capture.output to capture and write the output directly:
# Loop through each model summary and variable name for (i in seq_along(mlist_summ)) { current_var <- varlist[i] filename <- paste0("model_summary_", current_var, ".txt") # Capture the printed summary and write to file capture.output(print(mlist_summ[[i]]), file = filename) }
Key Notes:
seq_along(mlist_summ)gives us indices that align perfectly with bothmlist_summandvarlist(since they’re the same length from yourlapplycalls).- Customize filenames easily with
paste0—for example, add a date:paste0("model_", current_var, "_", Sys.Date(), ".txt"). - Verify your working directory with
getwd()to ensure files save where you expect; usesetwd()to adjust if needed.
内容的提问来源于stack exchange,提问作者Lumos

