Writing Data From R to txt|csv Files: R Base Functions


Previously, we described R base functions (read.delim() and read.csv()) for importing txt and csv files into R.

In this article, you’ll learn how to export or write data from R to .txt (tab-separated values) and .csv (comma-separated values) file formats.

Writing Data From R to txt|csv Files: R Base Functions

Preleminary tasks

R base functions for writing data

The R base function write.table() can be used to export a data frame or a matrix to a file.

A simplified format is as follow:

write.table(x, file, append = FALSE, sep = " ", dec = ".", row.names = TRUE, col.names = TRUE)

It’s also possible to write csv files using the functions write.csv() and write.csv2().

The syntax is as follow:

write.csv(my_data, file = "my_data.csv") write.csv2(my_data, file = "my_data.csv")

Writing data to a file

The R code below exports the built-in R mtcars data set to a tab-separated ( sep = “\t”) file called mtcars.txt in the current working directory:

# Loading mtcars data data("mtcars") # Writing mtcars data write.table(mtcars, file = "mtcars.txt", sep = "\t", row.names = TRUE, col.names = NA)

If you don’t want to write row names, use row.names = FALSE as follow:

write.table(mtcars, file = "mtcars.txt", sep = "\t", row.names = FALSE)

Summary

Related articles