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)
- 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:
The file contains the following data:
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
We can see that R imported the Excel file and automatically determined that team was a string variable while points and assists were numerical variables.
Related: How to Import CSV Files into R