Open In App

How to Remove Rows in R DataFrame?

In this article, we will discuss how to remove rows from dataframe in the R programming language.

Method 1: Remove Rows by Number

By using a particular row index number we can remove the rows.



Syntax:

data[-c(row_number), ]

where. 



Example:




# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
                age=c(21,23,21,10,22))
  
# display by removing 4 th row
print(data[-c(4), ])
  
# display by removing 5 th row
print(data[-c(5), ])
  
# display by removing 1 st  row
print(data[-c(1), ])

Output:

> print(data[-c(4), ])
    name age
1  manoj  21
2 manoja  23
3 manoji  21
5 manooj  22
> print(data[-c(5), ])
    name age
1  manoj  21
2 manoja  23
3 manoji  21
4   mano  10
> print(data[-c(1), ])
    name age
2 manoja  23
3 manoji  21
4   mano  10
5 manooj  22

We can also remove multiple rows by using the slice operator

Syntax:

data[-c(row_number_start:row_number_end), ]

where,

Example:




# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
                age=c(21,23,21,10,22))
  
# display by removing row from 1 st to 4 th
print(data[-c(1:4), ])
  
# display by removing row from 1 st to 2 nd
print(data[-c(1:2), ])

Output:

    name age
5 manooj  22
>
> # display by removing row from 1 st to 2 nd
> print(data[-c(1:2), ])
   name age
3 manoji  21
4   mano  10
5 manooj  22

We can also remove multiple rows by specifying multiple row indices

Syntax:

data[-c(row numbers), ]

Example:




# create a dataframe
data = data.frame(name=c("manoj", "manoja", "manoji", "mano",
                         "manooj"), age=c(21, 23, 21, 10, 22))
  
# display by removing 1,3,4 rows
print(data[-c(1, 3, 4), ])

Output:

    name age
2 manoja  23
5 manooj  22

Method 2: Remove rows conditionally

We can also use the conditions using subset() function

Syntax:

subset(dataframe,condition )

Example:




# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
                age=c(21,23,21,10,22))
  
# display by removing age less than 21
print(subset(data,age>21 ))

Output:

    name age
2 manoja  23
5 manooj  22

Method 3: Remove rows with NA values:

we can remove rows that contain NA values using na.omit() function from the given data frame.

Syntax:

na.omit(dataframe)

Example:




# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
                age=c(21,23,21,10,22))
  
# display by removing age less than 21
print(na.omit(data))

Output:

    name age
1  manoj  21
2 manoja  23
3 manoji  21
4   mano  10
5 manooj  22

Article Tags :