You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将回归模型列表中的各模型结果保存为独立文本文件?

Solution to Save Model Summaries as Individual Text Files

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 both mlist_summ and varlist (since they’re the same length from your lapply calls).
  • 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; use setwd() to adjust if needed.

内容的提问来源于stack exchange,提问作者Lumos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:30:36