Save All Console Input & Output to File in R (Example)
In this tutorial, I’ll show how to save the input and output of the RStudio console to a log file in the R programming language.
Table of contents:
Let’s dive right into the examples
Example: Creating txt-File Containing Log of RStudio Console
To create a log file of the RStudio console input and output is actually not as simple as it might sound. In the following, I’m therefore explaining how to save the RStudio console step by step.
First, we need to define the name of the log file we want to create. In this example, we’ll call it “my_log.txt”:
my_log <- file("my_log.txt") # File name of output log
Unfortunately, R doesn’t provide a function returning console input AND output at the same time (at least as far as I know). Therefore, we are first using the sink function to store the console output:
sink(my_log, append = TRUE, type = "output") # Writing console output to log file sink(my_log, append = TRUE, type = "message")
cat(readChar(rstudioapi::getSourceEditorContext()$path, # Writing currently opened R script to file file.info(rstudioapi::getSourceEditorContext()$path)$size))
The previous R codes have to be put at the beginning of your R script. Now, we can continue with any R syntax we want. Let’s produce some warnings, errors, and regular outputs:
1:10 + 1:5 # Some R code returning warnings x <- "my string" # Some data objects x # Print to console
Finally, we have to use the closeAllConnections function to stop printing to our log file:
closeAllConnections() # Close connection to log file
Have a look at your working directory. At this point, it should contain a txt log file looking like this:
The first part of the log file contains the R script itself (i.e. the console input) and the second part of the log file contains the RStudio console output.
Video, Further Resources & Summary
In case you need further information on the R code of this article, you might want to watch the following video of my YouTube channel. In the video, I show the R programming code of this tutorial.
The YouTube video will be added soon.
Furthermore, I can recommend to have a look at the other tutorials on this homepage. I have released several posts already:
- R sink Function
- Clear R and RStudio Console
- Print Character String to Newline of RStudio Console
- The R Programming Language
You learned in this article how to export the RStudio console in the R programming language. Let me know in the comments below, in case you have additional questions. Furthermore, don’t forget to subscribe to my email newsletter to get updates on new articles.