In this article we will work on exporting data frame to .csv file in R using write.csv() command.
Theory
We did our data manipulations in R and now our data frame contains all the information we were looking for.
Of course, we can keep working on it in R, but assume this was an ad-hoc task provided to your by your team members or management.
You did everything they asked, cleaned the data, renamed columns, merged columns, merged several tables, and all of other requirements.
You end up having a nice looking single data frame and now you need to share it with other people on your team.
Too bad that they work in different softwares and not everyone is using R. But you all agree that the file can be delivered in a .csv format to the team.
In this article I show an applied example on how to export data frame to a CSV file in R.
Application
Below are the steps we are going to take to make sure we do master the skill of exporting data frame to a .csv file in R:
- Basic write.csv() command description
- Creating a sample data frame in R
- Exporting data frame to a CSV file in R
Part 1. Basic write.csv() command description
The very brief theoretical explanation of the function is the following:
write.csv(data, “filepath”)
Here, “data” refers to the data frame you are working with; and “filepath” refers to the directory where you would like the .csv file to be exported to.
If you would like to learn the full description of the command, you can read about it here.
Part 2. Creating a sample data frame in R
For the purpose of this article we will create a data frame with information on two clients of the company: clients ID “1111” and “1112”.
You can create this sample data frames using the following code:
mydata<-data.frame(id = c("1111","1112"),
name = c("John Smith","Erik Johnson"),
city = c("Boston", "Buffalo"),
sales = c("$88,900", "$74,500"))
Now, we can take a look at the data frames we just created:
View(mydata)
Note: in this article I create my own datasets. If you have your own in a csv or excel files, you can follow the same procedure to arrive at the result.
Part 3. Exporting data frame to a CSV file in R
Our goal now is to take this dataset and export it to our computer as a .csv file.
I would like to export it to my desktop (note: I work on MacOS, so the formatting of the destination can be different from Windows).
Additionally, I would like to call the exported file "myfile.csv".
Using the above information, and knowing the structure of the write.csv() command, we can now export data frame to a CSV file in R!
You can do it using the following code:
write.csv(mydata, "/Users/DataSharkie/Desktop/myfile.csv")
Now, if you go to your "Desktop", you will fine the "myfile.csv" saved there.
If you are interested to learn more about importing/exporting different data formats, you can find more articles here.