Skip to content
Related Articles

Related Articles

Improve Article

How to read Excel file and select specific rows and columns in R?

  • Last Updated : 20 May, 2021

In this article, we will discuss how to read an Excel file and select specific rows and columns from it using R Programming Language.

File Used:

To read an Excel file into R we have to pass its path as an argument to read_excel() function readxl library.

Syntax:



read_excel(path)

To select a specific column we can use indexing.

Syntax:

df [ row_index , column_index ]

Here df represents data frame name or Excel file name or anything

Extracting specific rows from Excel file 

For this, we have to pass the index of the row to be extracted as input to the indexing. As a result, the row at the provided index will be fetched and displayed.

Example 1 :

R






library(readxl)
  
setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')
df=read_excel('OSWT1.xlsx')
  
a=df[5,]
print(a)

Output :

Example 2 :

R




library(readxl)
  
setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')
df=read_excel('OSWT1.xlsx')
  
a=df[6,]
print(a)

Output :

Example 3 :

R




library(readxl)
  
setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')
df=read_excel('OSWT1.xlsx')
  
a=df[7,]
print(a)

Output :



To get multiple rows similarly not much modification is required. The index of the rows to be extracted should be passed as a vector to the row_index part of indexing syntax.

Example 4 : 

R




library("readxl")
  
df=read_excel("C:/users/KRISHNA KARTHIKEYA/Documents/OSWT1.xlsx")
print(df[c(2,3),])

Output :

Extracting specific columns from Excel file 

This is similar to the approach followed above except that to extract the column index of the column needs to be given as an argument.

Example 1 :

R




library(readxl)
  
setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')
df=read_excel('OSWT1.xlsx')
  
a=df[,2]
print(a)

Output :



Example 2:

R




library(readxl)
  
setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')
df=read_excel('OSWT1.xlsx')
  
a=df[,3]
print(a)

Output : 

Example 3 :

R




library(readxl)
  
setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')
df=read_excel('OSWT1.xlsx')
  
a=df[,4]
print(a)

Output :

To get multiple columns at once the index of the columns to be extracted should be given as a vector in column_index part of the indexing syntax. All the columns with the index provided will be fetched and displayed.

Example 4 :

R




library("readxl")
  
df=read_excel("C:/users/KRISHNA KARTHIKEYA/Documents/OSWT1.xlsx")
  
print(df[,c(2,3)])

Output : 




My Personal Notes arrow_drop_up
Recommended Articles
Page :