How to Write CSV in R

less than 1 minute read

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:

getwd()

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

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

As an example lets say you have a data frame:

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:

# 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=",")

Leave a Comment