How to Import Excel Files into R (Step-by-Step)

To import an Excel file into R, the first step is to install the readxl package and then use the read_excel() function to import your file. Once the file is imported, you can use the View() function to view the contents of the file, and the str() function to explore the structure of the data. You can then use the filter() and select() functions to filter and select specific columns of data from the imported file. Finally, you can use the head() or tail() functions to view the first or last few rows of your data.


The easiest way to import an Excel file into R is by using the read_excel() function from the readxl package.

This function uses the following syntax:

read_excel(path, sheet = NULL)

where:

  • path: Path to the xls/xlsx file
  • sheet: The sheet to read. This can be the name of the sheet or the position of the sheet. If this is not specified, the first sheet is read.

This tutorial provides an example of how to use this function to import an Excel file into R.

Example: Import an Excel File into R

Suppose I have an Excel file saved in the following location:

C:UsersBobDesktopdata.xlsx

The file contains the following data:

Import Excel into R

The following code shows how to import this Excel file into R:

#install and load readxl package
install.packages('readxl')
library(readxl)

#import Excel file into R
data <- read_excel('C:\Users\Bob\Desktop\data.xlsx')

Note that we used double backslashes (\) in the file path to avoid the following common error:

Error: 'U' used without hex digits in character string starting ""C:U"

We can use the following code to quickly view the data:

#view entire dataset
data

#A tibble: 5 x 3
 team  points  assists
 <chr>   <dbl>   <dbl>
1 A         78      12
2 B         85      20
3 C         93      23
4 D         90       8
5 E         91      14

The following tutorials explain how to import other file types into R:

x