Export DataFrame to CSV in R Programming LanguageLast Update : 28 Sep, 2023
R programming language is a popular programming language for data analysis and manipulation. One essential operation in data analysis is exporting data to different file formats for sharing or further work. In this tutorial, you will learn how to export a DataFrame to a CSV file in R.
Loading Data into R
Before exporting data to a CSV file, let's first load a DataFrame. There are various methods to load data into R. For this example, we can create a simple DataFrame using the data.frame function as follows.
data <- data.frame( Name = c("Alex", "Aron", "Mike", "Shen"), Age = c(38, 35, 32, 32), Score = c(90, 80, 70, 90) )
Now you have sample data, let's try to export it to a CSV file.
Exporting data to CSV
R language provides an easy way to export a DataFrame to a CSV file using the write.csv function. The following example shows how you can do it.
write.csv(data, "my_data.csv", row.names = FALSE)
In this example,
- The write.csv() function is used for exporting data to a CSV file.
- data is the DataFrame you want to export to a CSV file.
- "my_data.csv" is the CSV file name that you want to create. You can replace it with any of your preferred file names and file path.
- row.names = FALSE specifies that you do not want to include row names in the CSV file. If you want to include row names, set it to TRUE.
After running this code, you can see a CSV file named "my_data.csv" in your working directory. This CSV file contains the data included in your sample DataFrame.
Customizing CSV Export
You can further customize the CSV export process according to your requirements. The following are a few examples.
If you have data with non-ASCII characters, you can specify the encoding using the fileEncoding argument.
The following shows the export with UTF-8 encoding.
write.csv(data, "my_data.csv", row.names = FALSE, fileEncoding = "UTF-8")
Controlling Decimal Places
If you need to control the number of decimal places in numeric columns, you can use the digits argument.
The following shows export with 4 decimal places.
write.csv(data, "my_data.csv", row.names = FALSE, digits = 4)
write.csv uses a comma as the delimiter as default. If you need to use a different delimiter, you can use the sep argument.
The following shows export with a semicolon(;) as the delimiter.
write.csv(data, "my_data.csv", row.names = FALSE, sep = ";")