Today i will teach you the step by step to import an Excel file into R?
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 may use this template:
library("readxl")
read_excel("Path where your Excel file is stored\\File Name.xlsx",sheet = "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 would look like in the R console:
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
Suppose that you have an Excel file with some data about products:
Product | Price |
Desktop Computer | 700 |
Tablet | 250 |
iPhone | 800 |
Laptop | 1200 |
And let’s say that 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 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\\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 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 Excel file:
library("readxl")
read_excel("C:\\Users\\Ron\\Desktop\\product_list.xlsx")
And this is how my code looked like in the R Editor:
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: