R sink Function (3 Examples) | Export R output as txt & csv File
In this article, I’ll explain how to use the sink function in R. I’ll show you in three examples how to:
- print text to a txt file (Example 1)
- export data as txt file (Example 2)
- export data as csv file (Example 3)
So without further ado, let’s dive into the examples…
Example 1: Export Character String as txt File
sink("example_1.txt") # Create empty txt file "some output" # Write text to file sink() # Close connection to file
…and then have a look at the following directory on your computer:
getwd() # Check current working directory # "C:/Users/...Your Path..."
In this folder you will find a txt file with the name example_1.txt. The file will look as follows:
Figure 1: Character String as txt File Output.
Explanation of the previous R code:
- In line 1 we created an empty txt file in the currently used folder.
- In line 2 we printed the character string some output. Without calling the sink function in the previous line of code, this character string would have been printed to the RStudio console. However, since we called the sink function before, the character string was printed to the txt file example_1.txt.
- In line 3 we closed the connection to the txt file.
Note: In line 2 of our R code, we could print basically everything we want – even data frames. And that’s what I’m going to show you in the next example…
Example 2: Export Data Frame as txt File
In the second example, we will use the R sink function to print an entire data frame to a txt file:
sink("example_2.txt") # Create empty txt file ChickWeight # Print ChickWeight data sink() # Close connection to file
Let’s have a look at the file:
Figure 2: Chicken Data as txt File Output.
As you can see in Figure 2, the entire ChickWeight data frame was exported as txt file.
Can we also use sink to export data in other formats than txt? Yes, we can…
Example 3: Export Data Frame as csv File
So far, we have exported different kinds of data as txt file. However, the sink command can also be used to export other data formats. In this example, we are going to export the ChickWeight data as csv file:
sink("example_3.csv") # Create empty csv file ChickWeight # Print ChickWeight data sink() # Close connection to file
Let’s have a look at the output file:
Figure 3: Chicken Data as Excel csv File Output.
Figure 3 show the csv file that we have just created with the sink function.
Video: More Examples for the sink Function
Do you want to see a few more examples for the sink function in R? No problem! The following video of the YouTuber Phil Chan shows how to redirect textual output to a file in R using the sink() command.
Have fun with the further examples of the video and let me know in the comments in case you have any questions!