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

R语言writeLines仅输出最后一行至文本文件的解决求助

解决R中多次writeLines仅写入最后一行的问题

问题原因

你的代码中使用file()创建文件连接时未指定打开模式,导致每次调用writeLines()时,R会重复打开文件并以覆盖模式写入,最终仅保留最后一次的输出内容。

解决方案1:显式指定文件连接的写入模式

修改文件连接的创建代码,添加open = "w"参数(表示以写入模式打开文件,若文件已存在则覆盖,后续写入会追加到文件末尾):

# Create a report file with write mode explicitly set
report_file <- file("XYZ.txt", open = "w")

# Write findings to the report file
writeLines("Report on Weather Analysis\n", report_file)

writeLines("\n3. Correlations between Weather Conditions and Departure Delays\n", report_file)
writeLines(paste("Correlation between Average Wind Speed and Departure Delays:", correlation_wind_speed), report_file)
writeLines(paste("Correlation between Wind Gust and Departure Delays:", correlation_wind_gust), report_file)
writeLines(paste("Correlation between Precipitation and Departure Delays:", correlation_precipitation), report_file)

# Close the report file
close(report_file)

解决方案2:合并内容后一次性写入

更简洁的方式是将所有需要输出的内容合并为一个字符向量,仅调用一次writeLines(),无需手动管理文件连接:

# Combine all content into a single character vector
report_content <- c(
  "Report on Weather Analysis\n",
  "\n3. Correlations between Weather Conditions and Departure Delays\n",
  paste("Correlation between Average Wind Speed and Departure Delays:", correlation_wind_speed),
  paste("Correlation between Wind Gust and Departure Delays:", correlation_wind_gust),
  paste("Correlation between Precipitation and Departure Delays:", correlation_precipitation)
)

# Write all content at once
writeLines(report_content, "XYZ.txt")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:22:12