How to Import an Excel File into R (example included)

Looking to import an Excel file into R?

In this short guide, I’ll show you the steps to import your file using the readxl package.

To start, here is a template that you can use to import an Excel file into R:

library("readxl")
read.excel("Path where your Excel file is stored\\File Name.xlsx")

And if you want to import a specific sheet within the Excel file, then you can use this template:

library("readxl")
read.excel("Path where your Excel file is stored\\File Name.xlsx",sheet = "Type here your sheet name") 

Note: For previous versions of Excel, use the file extension of .xls

Steps to Import an Excel file Into R

Step 1: Install the readxl package

In the R Console, type the following command to install the readxl package:

install.packages("readxl")

This is how the command should look like in the R console:

How to Import an Excel File into R (example included)

Follow the instructions to complete the installation. You may want to check the following guide that explains how to install packages in R.

Step 2: Prepare your Excel File

Suppose that you have an Excel file with some data about products:

ProductPrice
Desktop Computer700
Tablet250
iPhone800
Laptop1200

And let’s say that the name of your Excel file is Products, and your goal is to import that file into R.

Step 3: Import the Excel file into R

In order to import your file, you’ll need to apply the following template in the R Editor:

library("readxl")
read.excel("Path where your Excel file is stored\\File Name.xlsx")

In my case, I stored the Excel file on my Desktop under the following path:

C:\\Users\\Ron\\Desktop\\Products.xlsx

Where:

  • Products is the actual file name
  • .xlsx is the Excel file extension. For previous versions of Excel, use the file extension of .xls

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”

Putting everything together, this is the code that I used to import the file:

library("readxl")
read_excel("C:\\Users\\Ron\\Desktop\\Products.xlsx")

And this is how my code looked like in the R Editor:

How to Import an Excel File into R

You’ll need to adjust the path name to reflect the location where the Excel file is stored on your computer. Once you run the code in R, you’ll get the same values as in the Excel file:

Import Excel File into R

CategoriesR