How to Write CSV in R
I often write to CSV with R in order to save data and share files with others. One way to output a csv from R is with the command write.csv. Here is an example of how to write CSV in R:
# Write CSV in R write.csv(MyData, file = "MyData.csv")
The above writes the data data frame MyData into a CSV that it creates called MyData.csv. Note that the file is written to your working directory.
Most of the time I don’t want to include row names in the CSV. To omit the row names, I add a comma and then row.names=FALSE. row.names=F will also work if you’re into the whole brevity thing.
# Write CSV in R write.csv(MyData, file = "MyData.csv",row.names=FALSE)
Sometimes I also want to leave out the NAs. To omit NAs, add a comma and then na=””.
# Write CSV in R write.csv(MyData, file = "MyData.csv",row.names=FALSE, na="")
If you want to leave out the column names it is a little more complicated. write.csv is what is called a “convenience wrapper” and so has few features. Instead, use write.table and specify that sep=”,” and col.names=FALSE.
# Write CSV in R write.table(MyData, file = "MyData.csv",row.names=FALSE, na="",col.names=FALSE, sep=",")
There are other options that can be used with write.csv. Since write.csv is related to write.table, see official R-manual page on write.table to learn more: http://stat.ethz.ch/R-manual/R-devel/library/utils/html/write.table.html.
Thanks for reading! This website took a great deal of time to create. If it was helpful to you, please show it by sharing with friends, liking, or tweeting! If you have any thoughts regarding this R code please post in the comments.