How to Use write.table in R? 2

How to Use write.table in R?

The write.table function in R is a useful tool for exporting data frames or matrices into external files, such as text or CSV files. This function allows users to customize the formatting and structure of the output file, making it a flexible and efficient tool for data manipulation and analysis. By following a few simple steps, users can easily utilize the write.table function in R to export their data and create organized and easily readable files. The following examples demonstrate the various ways in which the write.table function can be used to save data in different formats, making it a valuable tool for data management in R.

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:UsersbobDesktopdata.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:UsersbobDesktopdata.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
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:UsersbobDesktopdata.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:

Cite this article

stats writer (2024). How to Use write.table in R?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-to-use-write-table-in-r-with-examples-2/

stats writer. "How to Use write.table in R?." PSYCHOLOGICAL SCALES, 1 May. 2024, https://scales.arabpsychology.com/stats/how-to-use-write-table-in-r-with-examples-2/.

stats writer. "How to Use write.table in R?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-to-use-write-table-in-r-with-examples-2/.

stats writer (2024) 'How to Use write.table in R?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-to-use-write-table-in-r-with-examples-2/.

[1] stats writer, "How to Use write.table in R?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, May, 2024.

stats writer. How to Use write.table in R?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top