Open In App

Specify Row Names when Reading Excel File in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to specify the row names when reading Excel file in the R Programming language.

Specifying row names when reading a file using row.names argument of the read.xlsx2() function.

This is the easiest approach to specify the row names when reading a file in the R programming language as in this approach the user needs to just call the read.xlsx() function which is particularly used for importing the excel type size, and used the row.names argument of this function with the required values into it and this will be reading to the specifying row names as per mentioned as the argument value with reading o file in the R programming language. Also, xlsx package, for this approach the user needs to install and import the xlsx package to the R working console as the function used here is from this package.

To install and import the xlsx package the user needs to follow the below syntax:

install.packages("xlsx")                            
library("xlsx")  

Read.xlsx2() function: This function is used to read data from an Excel file or Workbook object into data.frame

Syntax: read.xlsx(xlsxFile, sheet, startRow = 1, colNames = TRUE, rowNames = FALSE, detectDates = FALSE, skipEmptyRows = TRUE, skipEmptyCols = TRUE, rows = NULL, cols = NULL,check.names = FALSE, sep.names = “.”, namedRegion = NULL, na.strings = “NA”, fillMergedCells = FALSE,row.names)

Excel file for demonstration

We will be using the xlsx file of 6 rows and 5 columns and with the use of the row.names argument we will be specifying the row names to 1 while reading this file.

R




library(xlsx)
  
gfg_file = read.xlsx2("GFG_DATA.xlsx"
                      sheetIndex = 1,
                      row.names = 1)
gfg_file


Output:

Specify Row Names when Reading a File

We will be using the xlsx file of 6 rows and 5 columns same as used in the previous example and with the use of the row.names argument we will specify the row names to 4 while reading this file.

R




library(xlsx)
  
gfg_file = read.xlsx2("GFG_DATA.xlsx",
                      sheetIndex = 1,
                      row.names = 4)
gfg_file


Output:



Last Updated : 31 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads