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]]
#  [1]  1  2  3  4  5  6  7  8  9 10
# 
# [[2]]
#  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
# 
# [[3]]
# [1] "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:

 

CSV file shows list

 

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:

 

TXT file shows list

 

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.

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top