BLOG

Write CSV in R

03-06-2019  0 Comment(s)

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 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.

Comment Here

Comments

No Comments to Show

WE ALWAYS WORK WITH :