Home » How to Export List to a File in R (With Examples)

How to Export List to a File in R (With Examples)

by Erma Khan

You can use the sink() function to quickly export a list to a CSV file or text file in R.

The following examples show how to use this function in practice with the following list:

#create list
my_list 

#view list
my_list

$A
[1] 1 5 6 6 3

$B
[1] "hey"   "hello"

$C
 [1]  1  2  3  4  5  6  7  8  9 10

Related: A Gentle Introduction to the sink() Function in R

Example 1: Export List to Text File

We can use the following sink() function to export the list to a text file:

#define file name
sink('my_list.txt')

#print my_list to file
print(my_list)

#close external connection to file 
sink()

We can then navigate to the current working directory and open the text file:

The text file contains the list formatted exactly as it was in R.

We can also use multiple print statements within the sink function to export multiple lists to one text file:

#create multiple lists
my_list1 

#define file name
sink('my_lists.txt')

#print multiple lists to file
print(my_list1)
print(my_list2)

#close external connection to file 
sink()

We can then navigate to the current working directory and open the text file:

The text file contains both lists.

Example 2: Export List to CSV File

We can use the following sink() function to export the list to a CSV file:

#define file name
sink('my_list.csv')

#print my_list to file
print(my_list)

#close external connection to file 
sink()

We can then navigate to the current working directory and open the CSV file:

The CSV file contains the list formatted exactly as it was in R.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Export a Data Frame to an Excel File in R
How to Export a Data Frame to a CSV File in R
How to Use write.table in R

Related Posts