Table of Contents
Write.table in R is a function that can be used to write data to a file in a tabular format. The data can be exported to a text file, a csv file, or an Excel spreadsheet. To use the write.table function, you must specify the data frame that you want to write, the file name, the separator (comma, tab, etc.), and the row names. Additionally, you can choose to include columns names as headers and also write the output to the console. Examples of how to use write.table can be found in the R documentation.
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.
Related:
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 df 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: