How to Import a CSV File into R (example included)

In this short post, I’ll show you how to import a CSV file into R. I’ll also include a simple example to demonstrate this concept.

But before we begin, here is the general syntax that you may apply in R in order to import your CSV file:

 

read.csv('Path where your CSV file is located on your computer\\File Name.csv')

 

Let’s now review a simple example.

Example used to import a CSV file into R

Let’s say that you have the following data stored in a CSV file (where the file name is ‘Employees’):

 

Employee First NameEmployee Last Name
JackJones
MariaGreen
BillYu
EvaTaylor
MarkLee

 

Our goal is to import that CSV into R.

In my case, I stored the ‘Employees’ CSV file on my desktop, under this path:

C:\\Users\\Doron E\\Desktop\\Employees.csv

Notice that I highlighted two portions within that path:

  • The blue portion represents our ‘Employees’ file name. You need to make sure that the name is identical to the actual file name to be imported
  • While the green portion reflects our file type of csv. Do not forget to add that portion when dealing with CSV files

Also note that I used double backslash (‘\\’) within the path name. By adding double backslash I avoided the following error in R:

Error: ‘\U’ used without hex digits in character string starting “”C:\U”

This is one workaround that you may apply in R to bypass this type of error.

Here is the full code to import a CSV file into R (you’ll need to modify the path name to the location where your CSV file is stored on your computer):

 

read.csv('C:\\Users\\Doron E\\Desktop\\Employees.csv', header = TRUE)

 

Notice that I also set the header to ‘TRUE’ as our data-set in the CSV file contains header.

Finally, run the code in R and you should get the same values as in the CSV file:

 

How to Import a CSV File into R

 

But wait a minute, what if you want to import a text file into R?

If that’s the case, you only need to change the file extension from csv to txt (at the end of the path). In my case, the path name should look like this:

 

read.csv('C:\\Users\\Doron E\\Desktop\\Employees.txt', header = TRUE)

 

Once you run that code (adjusted to your path name), you should get the same imported data into R.

That’s it! You may want to check the Read.csv documentation for further information about importing a CSV file into R.

Finally, you may also want to review the opposite case of exporting data to a CSV file in R.

 

CategoriesR