To import an Excel file into R using the readxl package:
library("readxl") df = read_excel("Path where your Excel file is stored\\File Name.xlsx") print(df)
To import a specific sheet within the Excel file:
library("readxl") df = read_excel("Path where your Excel file is stored\\File Name.xlsx", sheet="Your sheet name") print(df)
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")
Follow the instructions to complete the installation.
You may want to check the following guide that explains how to install a package in R.
Step 2: Prepare your Excel File
Let’s suppose that you have an Excel file with some data about products:
Product | Price |
Refrigerator | 1200 |
Oven | 750 |
Dishwasher | 900 |
Coffee Maker | 300 |
And let’s say that the Excel file name is product_list, 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 use the following template in the R Editor:
library("readxl") df = read_excel("Path where your Excel file is stored\\File Name.xlsx") print(df)
For demonstration purposes, let’s assume that an Excel file is stored under the following path:
C:\\Users\\Ron\\Desktop\\Test\\product_list.xlsx
Where:
- product_list is the actual file name; and
- .xlsx is the Excel file extension. For previous versions of Excel, use the file extension of .xls
Note that a double backslash (‘\\’) was used within the path name. By adding a 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 complete code to import the Excel file for our example:
library("readxl") df = read_excel("C:\\Users\\Ron\\Desktop\\Test\\product_list.xlsx") print(df)
You’ll need to adjust the path 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:
Product Price
1 Refrigerator 1200
2 Oven 750
3 Dishwasher 900
4 Coffee Maker 300
Alternatively, you may check the following guide that explains how to export your data to an Excel file.