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

To import a CSV file into R:

df = read.csv("Path where the CSV file is stored\\File Name.csv")

print(df)

Example of importing 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‘):

item_nameprice
Desk400
Tablet150
Printer85
Laptop1300
TV1500

The goal is to import that CSV file into R.

For demonstration purposes, let’s assume that the ‘Products‘ CSV file is stored under the following path:

C:\\Users\\Ron\\Desktop\\Test\\Products.csv

Where:

  • The file name (as highlighted in blue) is Products
  • The file type (as highlighted in green) is .csv
  • Double backslash (‘\\’) was applied within the path to avoid errors when importing files

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

df = read.csv("C:\\Users\\Ron\\Desktop\\Test\\Products.csv")

print(df)

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:

df = read.csv("C:\\Users\\Ron\\Desktop\\Test\\Products.txt")

print(df)

Once you run that code (adjusted to your path ), you’ll get the same imported data.

You may want to check the Read.csv documentation for additional information about importing a CSV file in R.

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

Leave a Comment