Writing text and output from analyses to a file

Problem

You want to write output to a file.

Solution

The sink() function will redirect output to a file instead of to the R terminal. Note that if you use sink() in a script and it crashes before output is returned to the terminal, then you will not see any response to your commands. Call sink() without any arguments to return output to the terminal.

  1. # Start writing to an output file
  2. sink('analysis-output.txt')
  3. set.seed(12345)
  4. x <-rnorm(10,10,1)
  5. y <-rnorm(10,11,1)
  6. # Do some stuff here
  7. cat(sprintf("x has %d elements:\n", length(x)))
  8. print(x)
  9. cat("y =", y, "\n")
  10. cat("=============================\n")
  11. cat("T-test between x and y\n")
  12. cat("=============================\n")
  13. t.test(x,y)
  14. # Stop writing to the file
  15. sink()
  16. # Append to the file
  17. sink('analysis-output.txt', append=TRUE)
  18. cat("Some more stuff here...\n")
  19. sink()

The contents of the output file:

  1. x has 10 elements:
  2. [1] 10.585529 10.709466 9.890697 9.546503 10.605887 8.182044 10.630099 9.723816
  3. [9] 9.715840 9.080678
  4. y = 10.88375 12.81731 11.37063 11.52022 10.24947 11.8169 10.11364 10.66842 12.12071 11.29872
  5. =============================
  6. T-test between x and y
  7. =============================
  8. Welch Two Sample t-test
  9. data: x and y
  10. t = -3.8326, df = 17.979, p-value = 0.001222
  11. alternative hypothesis: true difference in means is not equal to 0
  12. 95 percent confidence interval:
  13. -2.196802 -0.641042
  14. sample estimates:
  15. mean of x mean of y
  16. 9.867056 11.285978
  17. Some more stuff here...