Import a .csv file in R

CSV importation: a native feature in R

Two function to import .csv files in R environment:  read.csv() and read.table().

Import a .csv. file in R with read.csv()

The read.csv() function is the native function for R. Here is how it works.

myDataset <- read.csv(CSVfile)

This instruction will transform your .csv file in a dataset. It will be saved on your global environment with the name myDataset. You will be able to explore its data and manipulate them on your R scripts. Other parameters are available to go further with the read.csv() function.

header = TRUE # By default, the first line is the header of the dataset

sep = "," # By default, the comma is used as a separator
quote = "\"" # By default, the character " is a quote
dec = "." # By default, the character . is used for the decimals

These parameters can be very important, for example for the importation of .csv files that doesn't match with the same decimal norm.

To avoid these issues of compatibility, you can use the variant read.csv2() that use the parameter sep = ";" and dec = "," by default. The read.csv2() function is adapted for data separated by ;.

Import a .csv file with read.table()

The read.table() function has the same comportment that the read.csv() function. Indeed, read.csv() looks like a version of read.table() with parameters adapted to read CSV files.

To read a .csv. file with read.table(), the structure is the same:


However, the function read.table() doesn't mention by default separators used. On. .csv file. The previous instruction will save a dataset with one column without header.

To get the same result as with the read.csv() function and get a separated dataset, you have to edit the following parameters.

read.table(file, header = TRUE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "")

The read.table() function will be more adapted to unconventional file type, else if the parameters of the read.csv() function can avoid this kind of issue.