Published on
220 words2 min read––– views

How to Write CSV in R

How to Write CSV in R

It's always better to write CSV with R after data preparation or cleaning in order to save the data for further analysis and to share with others.

Before writing any data frame or matrix to CSV, check the default working directory of your machine by the following command:

r
getwd()

You can change your default working directory by the following command:

r
# Windows:
setwd("C://DataScience//R")
# MAC:
setwd("/Users/Faisal/Desktop/")

As an example lets say you have a data frame:

r
my.data <- read.csv("messydata.csv")

Now suppose you have cleaned or prepared the data frame, and you want to save the data frame. You can do that by the following command:

r
# Write CSV in R with row name and column name:
write.csv(my.data, file = "PreparedData.csv")
# Write CSV in R without row name and with column name:
write.csv(my.data, file = "PreparedData.csv",row.names=FALSE)
# Write CSV in R without row name, with column name and to omit NA's:
write.csv(my.data, file = "PreparedData.csv",row.names=FALSE, na="")
# Write CSV in R without row and column name and to omit NA's:
write.table(my.data, file = "PreparedData.csv",row.names=FALSE, na="",col.names=FALSE, sep=",")