How to Read CSV in R
If you are using R much you will likely need to read in data at some point. While R can read excel .xls and .xlsx files these filetypes often cause problems. Comma separated files (.csv) are much easier to work with. It’s best to save these files as csv before reading them into R. If you need to read in a csv with R the best way to do it is with the command read.csv. Here is an example of how to read CSV in R:
# Read CSV into R MyData <- read.csv(file="c:/TheDataIWantToReadIn.csv", header=TRUE, sep=",")
The above reads the file TheDataIWantToReadIn.csv into a data frame that it creates called MyData. header=TRUE specifies that this data includes a header row and sep=”,” specifies that the data is separated by commas (though read.csv implies the same I think it’s safer to be explicit).
Note that the above includes the file path (the c:/). If you’ve already set a working directory in R you can just list the file, like this:
# Read CSV into R MyData <- read.csv(file="TheDataIWantToReadIn.csv", header=TRUE, sep=",")
There are other options that can be used with read.csv. See official R-manual page on read.csv to learn more: http://cran.r-project.org/doc/manuals/R-data.html.
Why not read.table?
I’ve found read.csv to be more reliable. I sometimes get errors with read.table. I’ll post the errors when I come across them again.
To practice reading csv data in R, try the exercises in this importing data in R tutorial.
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.