Export List to CSV or TXT File in R (2 Examples)
In this R article you’ll learn how to write a list object to an external file.
Table of contents:
Let’s jump right to the examples…
Creating Example Data
We’ll use the following data as basement for this R tutorial:
my_list <- list(1:10, # Create example list letters[1:10], c("x", "LALA", "abc")) my_list # Print example list in R # [] #  1 2 3 4 5 6 7 8 9 10 # # [] #  "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" # # [] #  "x" "LALA" "abc" #
The previous output of the RStudio console shows that the example data is a list object consisting of three list elements.
Example 1: Export List to CSV File
In Example 1, I’ll illustrate how to write our example list to a CSV file.
For this, we can use the capture.output function as shown below:
capture.output(my_list, file = "my_list.csv") # Apply capture.output
After running the previous R code, you should find a CSV file as the one below on your computer:
Example 2: Export List to TXT File
This example explains how to save a list as TXT file.
We can apply basically the same code as in Example 1. The only difference is that we have to specify the txt file extension within the capture.output function:
capture.output(my_list, file = "my_list.txt") # Apply capture.output
Have a look at your current working directory – You should find a TXT file looking like this:
Video, Further Resources & Summary
Would you like to learn more about lists in R? Then I recommend watching the following video of my YouTube channel. In the video, I show the R programming syntax of this article.
The YouTube video will be added soon.
In addition, you may read some of the related tutorials of my website. I have released several posts about exporting data already.
- scan Function (5 Example Codes)
- Export CSV File without Row Names in R
- sink Function in R
- The R Programming Language
Summary: This article has shown how to export a list as CSV or TXT in the R programming language. If you have additional questions and/or comments, let me know in the comments section. In addition, don’t forget to subscribe to my email newsletter to get updates on new tutorials.