Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r programming
communitycreator

How to use read_excel() to read Excel files in R

Salman Yousaf

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

  1. Install the module (optional) install.packages("readxl")
  2. Import the module library("readxl")
  3. Specify the path of the file to the read_excel() method
  4. Read the file with data <- read_excel("dataset.xlsx")
  5. 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 is TRUE.
    • 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 is NULL.
    • 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 specify na to 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 available
install.packages("readxl")
library("readxl") # library for read_excel() method
data <- read_excel("dataset.xlsx")
print(data)

Explanation

  • Program #1: To read an Xlsx or Xls file, we can use the read_excel() method from the readxl package (lines 1 and 2). We specify the necessary parameters like path_name or file_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.

Expected Output

RELATED TAGS

r programming
communitycreator
RELATED COURSES

View all Courses

Keep Exploring