Are you looking to export DataFrame to CSV in R?
If so, I’ll show you how to accomplish this task using a simple example.
To start, here is the generic syntax that you may use to export DataFrame to CSV in R:
write.csv(Your DataFrame,"Path where you'd like to export the DataFrame\\File Name.csv", row.names = FALSE)
And if you want to include the row.names, simply change it to TRUE.
In the next section, I’ll review an example with the steps to export your DataFrame.
Steps to Export DataFrame to CSV in R
Let’s say that you have the following data-set:
Your goal is to export that data-set to CSV. But before you can do that, you’ll need to capture this data in R in the form of a DataFrame.
Step-1: Create a DataFrame
To create a DataFrame in R, you may use this structure:
df <- data.frame(Column1 = c('Value 1', 'Value 2', 'Value 3'), Column2 = c('Value 1', 'Value 2', 'Value 3')) print (df)
Note that it’s not necessary to use quotations for numeric values.
And once you apply this structure for our example, you’ll get:
df <- data.frame(name = c('Jon', 'Bill', 'Maria'), age = c(23,41,32)) print (df)
Step-2: Use write.csv to Export the DataFrame
Next, you’ll need to include the code to export the DataFrame to CSV in R.
To do that, simply use the generic syntax that we saw at the beginning of this post. You’ll need to include the path name that corresponds to your computer.
Here, I decided to export the DataFrame to my Desktop, where my path name is:
And the full code to export DataFrame to CSV in R is:
df <- data.frame(name = c('Jon', 'Bill', 'Maria'), age = c(23, 41, 32)) write.csv(df,'C:\\Users\\Doron E\\Desktop\\MyData.csv', row.names = FALSE)
Pay attention to several highlighted portions in the path name:
- The blue portion represents the file name to be created. In our example, I chose to use the file name of ‘MyData’
- While the green portion reflects our file type of CSV. Don’t forget to add that portion when dealing with CSV files. Alternatively, you may use the file type of ‘txt’ to export the DataFrame as a text file instead.
You may also want to use double backslash (‘\\’) within the path name. By adding double backslash you would avoid the following error in R:
Error: ‘\U’ used without hex digits in character string starting “”C:\U”
Step-3: Run the code to Export the DataFrame to CSV
Run the code in R, once you modified the path name to the location where you’d like to store the DataFrame on your computer.
A new CSV file would be created at your specified location. The data within that file should match with our DataFrame created in R:
We just saw how to export DataFrame to CSV in R. At times, you may face an opposite situation, where you’ll need to import a CSV file into R.
If that’s the case, you may want to visit the following source that explains how to import a CSV file into R.
Finally, the Data Output documentation is a good source to check for additional information about exporting CSV files in R.