Skip to content
Related Articles

Related Articles

Improve Article

How to Delete Row(s) in R DataFrame ?

  • Last Updated : 09 May, 2021

In this article, we will see how row(s) can be deleted from a Dataframe in R Programming Language.

Deleting a single row

For this, the index of the row to be deleted is passed with a minus sign.

Syntax:

df[-(index), ]

Example 1 : 



R




# creating a data frame with
# some data .
df=data.frame(id=c(1,2,3),
              name=c("karthik","sravan","nikhil"),
              branch=c("IT","IT","CSE"))
  
# using - with indexing deleting
# 3rd row .
df[-3,] 

Output :

Example 2 : 

R




# creating a data frame with 
# some data .
df=data.frame(id=c(1,2,3),
              name=c("karthik","sravan","nikhil"),
              branch=c("IT","IT","CSE"))
  
# using - with indexing deleting 
# 2nd row
df[-2,] 

Output :

Deleting multiple rows

Method 1: Using Range



For this, the range of the rows to be deleted is passed to the dataframe name.

Syntax:

df[-(start_index,end_index), ]

Example 1: 

R




# creating a data frame with 
# some data
df=data.frame(id=c(1,2,3,4,5),
                
              name=c("karthik","sravan","nikhil",
                     "bhagiradh","sai"),
                
              branch=c("IT","IT","CSE","IT","CSE"))
  
# deleting multiple rows using 
# vector 
df[-c(3,5),] 

Output:

Image

Example 2: 

R




# creating a data frame with 
# some data
df=data.frame(id=c(1,2,3,4,5),
                
              name=c("karthik","sravan","nikhil",
                     "bhagiradh","sai"),
                
              branch=c("IT","IT","CSE","IT","CSE"))
  
# deleting multiple rows using 
# vector
df[-c(2,4),] 

Output :



Method 2: Using anti_join( )

anti_join method is available in dplyr package. So we have to install dplyr package first. To install we can use install.package() method, and we have to pass package name as parameter. To import the package into the R environment we need to use library( ) function. In this function, we have to pass the package name as a parameter.

Syntax : 

anti_join (data_frame_name , data_frame_name [ c(row_index 1 ,…row_index n),c( column_index 1,……column_index n)] )

Example 1 :

R




library(dplyr)
  
# creating a data frame with some data
df=data.frame(id=c(1,2,3,4,5),
                
              name=c("karthik","sravan","nikhil",
                     "bhagiradh","sai"),
                
              branch=c("IT","IT","CSE","IT","CSE"))
  
anti_join(df,df[c(1,2),])

Output :

Image

Example 2:

R




library(dplyr)
  
# creating a data frame with 
# some data
df=data.frame(id=c(1,2,3,4,5),
                
              name=c("karthik","sravan","nikhil",
                     "bhagiradh","sai"),
                
              branch=c("IT","IT","CSE","IT","CSE"))
  
anti_join(df,df[c(1,3),])

Output :

Image




My Personal Notes arrow_drop_up
Recommended Articles
Page :