In this article, we will show you how to write CSV file in R. If we’re familiar with R, we can leverage it to support us in getting, cleaning and processing data. After that, we can export R into different file formats for our further processing. CSV is one of popular format with which we want to come in this tutorial.
1. Write CSV in R
we can use R base functions to write CSV file without installing any other packages.
1.1. Write CSV in R using write.csv() function
To write CSV file which includes the header row and fields separated by commas, we can use the following command:
1 |
write.csv(df, file = "D:\\tmp\\data\\data.csv") |
The df is the data frame we want to write to the CSV file.
To write CSV file that doesn’t include the row names, we can add the row.names=FALSE option to the function.
1 |
write.csv(df, file = "D:\\tmp\\data\\data.csv", row.names=FALSE) |
When manipulating with the data frame, we may deal with a lot of NA(s) values, to omit those values when we write the data to CSV file, we can add the na=”” option to the function.
1 |
write.csv(df, file = "D:\\tmp\\data\\data.csv", row.names=FALSE, na="") |
1.2. Write CSV file in R using write.csv2() function
Another function can be used to write CSV file is write.csv2(). In similar to the read.csv2() function, write.csv2() uses a comma for the decimal point and a semicolon for the separator.
To write CSV file which includes the header row and fields separated by the semicolon, we can use the following command:
1 |
write.csv2(df, file = "D:\\tmp\\data\\data.csv") |
To write the CSV file that doesn’t include the row names, we can add the row.names=FALSE option to the function.
1 |
write.csv2(df, file = "D:\\tmp\\data\\data.csv", row.names=FALSE) |
1.3. Write CSV file in R using write.table() function
We can also use write.table() function to write CSV file in R. This function is more generic than write.csv() and write.csv2() functions. It can be used to write much different text file type.
To write CSV file with field separators are commas, excluded row names, excluded column names and omitted NA values, we can issue the below command:
1 |
write.table(df, file = "D:\\tmp\\data\\data1.csv",row.names=FALSE, na="",col.names=FALSE, sep=",") |
If we want to keep the row names and column names, we simply use the command:
1 |
write.table(df, file = "D:\\tmp\\data\\data1.csv", sep=",") |
2. Summary
We have learned to write CSV file in R by using R base functions. The write.csv(), write.csv2() and write.table() can be used to write CSV file. Note that the write.table() function to write different types of text files in R.
Here are other posts related to process data in R, you may refer to them if you’re interested in:
R Data Frame and basic functions
R – Rename Column of Data Frame
R – Add New Column To A Data Frame