Sometimes we need to export our results or data to other software. In this tutorial, you’ll learn how to export or write data from R or RStudio to .txt (tab-separated values), .csv (comma-separated values) and .xlsx (excel) file formats.

Exporting results from R program is usually a less contentious task. Before we start, we need to specify the working directory in which we can export the data.

## [1] "D:/DataScience"

Check Out: How to Change Working Directory in R

First of all, we first need to have data to write. For this tutorial, we will use iris data set as an example. The below is some portion of the data.

##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

Also Check: How to Import Data into R

1. How to Export Data from R to CSV

We use write.csv() function to write R data to .csv file. The command can be used as follows:

write.csv(iris, file = "iris.csv")

2. How to Export Data from R to TXT

Writing Data from R to .txt file is conducted with write.table() function. The command of exporting data to .txt format is available below.

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

Here, separator is tab character (\t). This means using the above command, tabular data can be written to the clipboard.

Also Check: What are Data Structures in R?

3. How to Export Data from R to Excel

Writing Data from R to Excel is implemented with write.xlsx() function in xlsx package (Dragulescu and Arendt, 2020). Also, the sheetname can be specified. append argument is important to write different sheets in one excel file. Here, we write complete data under the sheet name “Complete” in iris.xlsx file.

write.xlsx(iris, file = "iris.xlsx", sheetName="Complete", append = TRUE)

Then, we can write all iris species in different sheets of iris.xlsx file.

write.xlsx(iris[1:50,], file = "iris.xlsx", sheetName = "Setosa", append = TRUE)

write.xlsx(iris[51:100,], file = "iris.xlsx", sheetName = "Versicolor", append = TRUE)

write.xlsx(iris[101:150,], file = "iris.xlsx", sheetName = "Virginica", append = TRUE)

After that, we have an excel file including four sheets; Complete, Setosa, Versicolor, Virginica.

Let’s check the data sets that we have written in our working directory.

## [1] "iris.csv"  "iris.txt"  "iris.xlsx"

The application of the codes is available in our youtube channel below.

How to Export Data from R Using RStudio
Subscribe to YouTube Channel

Don’t forget to check: What are Data Types in R?


Dragulescu, A., Arendt, C. (2020). xlsx: Read, Write, Format Excel 2007 and Excel 97/2000/XP/2003 Files. R package version 0.6.5.