0

I'm trying to output my analysis from my R code through multiple write-commands as mentioned below. However, I am getting only one last line output to my text file.

Code:

# Create a report file
report_file <- file("XYZ.txt")

# 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)

I have also added the output provided through above lines of code from the text file.enter image description here

I am getting only one last line output to my text file. I need all my writeLines details in the output file. Please advice, if anyone has any expertise in this regards? Thanks in advance.

Mark
  • 7,785
  • 2
  • 14
  • 34
Manish
  • 1
  • Does this answer your question? [Write lines of text to a file in R](https://stackoverflow.com/questions/2470248/write-lines-of-text-to-a-file-in-r) – R. Schifini Jul 08 '23 at 02:18
  • 2
    Each call to `writeLines` is over-writing the file. You need to use a connection (see the previous comment), combine all strings into one vector, or use `write(..., append=TRUE)`` function – r2evans Jul 08 '23 at 03:04

1 Answers1

0

The problem is that you didn't open the connection, so R will open it and close it on each write operation, overwriting what was there before. Change the first line to

report_file <- file("XYZ.txt", open = "wt")

and it should work. The "wt" specification says "write as text". It would also be fine to say "w", but I find the explicit t makes the intention clearer. Other possibilities are described in the "Modes" section of the help page ?file.

user2554330
  • 37,248
  • 4
  • 43
  • 90