How to use read_excel() to read Excel files in R
In this shot, we will go over how to use the read_excel() method to read an Excel file in R. The read_excel() method is used to read an Excel file. In order to use this method, you first have to import the readxl library in your R program.
Approach
- Install the module (optional)
install.packages("readxl") - Import the module
library("readxl") - Specify the
pathof the file to theread_excel()method - Read the file with
data <- read_excel("dataset.xlsx") - Display the content of the file with
print(data)
Syntax
read_excel("path",sheet=1,col_names= TRUE,col_types=NULL,na="",skip= 0)
Parameters
path: Directory or path of excel file.sheet: Either the name of the sheet in the Excel file or index number. The default is 1.col_names: Default isTRUE.TRUE: Read the first row as a file header.FALSE: File does not have a header.Character Vector: A character vector that contains header names.
col_types: Default isNULL.NULL: Detects the type of column from the spreadsheet.Vector: A vector that contains “blank”, “numeric”, “date”, or “text.”
na: Keeps empty cells as is, but we can specifynato fill empty cells. The default is"".skip: Number of rows to skip from start before reading a file. The default is 0.
Example
# Install readxl package if not availableinstall.packages("readxl")library("readxl") # library for read_excel() methoddata <- read_excel("dataset.xlsx")print(data)
Explanation
- Program #1: To read an
XlsxorXlsfile, we can use theread_excel()method from thereadxlpackage (lines 1 and 2). We specify the necessary parameters likepath_nameorfile_name, if the program and file are in the same directory. - Program #2: This parameterized method will produce the same output as below. The difference is that Program #1 installs the library and Program #2 does not. Program #2 also adds more optional parameter values to the
read_excel()method.
Output
The code above provides dataset.xlsx as an argument file and produces the following output.