How to delete rows in an R data frame?


This can be done by using square brackets.

Example

> data<-data.frame(matrix(rnorm(50,5),nrow=10))
> data
   X1       X2       X3       X4       X5
1 4.371434 6.631030 5.585681 3.951680 5.174490
2 4.735757 4.376903 4.100580 4.512687 4.085132
3 4.656816 5.326476 6.188766 4.824059 5.401279
4 3.487443 4.253042 5.277751 6.121441 4.925158
5 5.174943 3.704238 5.813336 5.224412 4.990136
6 3.461819 5.102038 6.094579 5.536754 6.311731
7 4.772712 6.445479 5.254032 4.430560 7.183776
8 5.366510 5.232044 5.422526 3.746559 4.810256
9 4.786759 4.665812 4.634238 6.511210 4.959757
10 6.731195 5.083179 4.969842 4.976357 4.939117

Let’s say we want to remove rows 4, 7, and 9. We will do it as follows −

> data<-data[-c(4,7,9),]
> data
      X1    X2       X3       X4       X5
1  4.371434 6.631030 5.585681 3.951680 5.174490
2  4.735757 4.376903 4.100580 4.512687 4.085132
3  4.656816 5.326476 6.188766 4.824059 5.401279
5  5.174943 3.704238 5.813336 5.224412 4.990136
6  3.461819 5.102038 6.094579 5.536754 6.311731
8  5.366510 5.232044 5.422526 3.746559 4.810256
10 6.731195 5.083179 4.969842 4.976357 4.939117

Updated on: 06-Jul-2020

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements