In this short guide, you’ll see how to import a CSV file into R. An example is also included to demonstrate this concept.
But before we begin, here is a template 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 ‘Products‘):
The goal is to import that CSV into R.
For demonstration purposes, let’s assume that the ‘Products‘ CSV file is stored under the following path:
Notice the two portions highlighted in that path:
- The blue portion represents the ‘Products‘ file name. You’ll need to ensure that the name is identical to the actual file name to be imported
- The green portion reflects the file type of .csv. Don’t forget to add that portion when improting CSV files
Also note that double backslash (‘\\’) was used within the path name. By adding double backslash you’ll avoid the following error in R:
Error: ‘\U’ used without hex digits in character string starting “”C:\U”
Here is the full code to import the CSV file into R (you’ll need to modify the path name to reflect the location where the CSV file is stored on your computer):
Finally, run the code in R (adjusted to your path), and you’ll get the same values as in the CSV file:
Item_Name Price 1 Desk 400 2 Tablet 150 3 Printer 85 4 Laptop 1300 5 TV 1500
What if you want to import a text file into R?
In that case, you only need to change the file extension from csv to txt (at the end of the path). For example:
Once you run that code (adjusted to your path ), you’ll get the same imported data into R.
You may want to check the Read.csv documentation for further information about importing a CSV file in R.
Finally, you may review the opposite case of exporting data to a CSV file in R.