How to Use write.table in R (With Examples)

You can use the write.table function in R to export a data frame or matrix to a file.

This function uses the following basic syntax:

write.table(df, file='C:\\Users\\bob\\Desktop\\data.txt')

By default, the values in the exported file are separated by a single space but you can use the sep argument to specify a different delimiter.

For example, you could choose to use a comma as a delimiter:

write.table(df, file='C:\\Users\\bob\\Desktop\\data.txt', sep=',')

The following step-by-step example shows how to use this function in practice.

Step 1: Create a Data Frame

First, let’s create a data frame in R:

#create data frame
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, 3, 2),
                 var3=c(3, 3, 6, 6, 8),
                 var4=c(1, 1, 2, 8, 9))

#view data frame

  var1 var2 var3 var4
1    1    7    3    1
2    3    7    3    1
3    3    8    6    2
4    4    3    6    8
5    5    2    8    9

Step 2: Use write.table() to Export the Data Frame

Next, let’s use write.table() to export the data frame to a file called data.txt located on my Desktop:

#export data frame to Desktop
write.table(df, file='C:\\Users\\bob\\Desktop\\data.txt')

Step 3: View the Exported File

Next, I can navigate to my Desktop and open the file called data.txt to view the data:

Notice that the values in the file are separated by single spaces since we didn’t specify a different delimiter when we exported the data frame.

Additional Resources

How to Export a Data Frame to an Excel File in R
How to Export a Data Frame to a CSV File in R

Leave a Reply

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