R lang provides the – operator to remove rows from dataframe. Simply provide the indexes of rows to remove with – sign.

Consider this example –

mydata <- data.frame(A=c(1,2,3,4), B=c('a', 'b', 'c', 'd'), C=c('Q', 'W', 'E', 'R'))
mydata

  A B C
1 1 a Q
2 2 b W
3 3 c E
4 4 d R

Here we have created a dataframe with 4 rows and 3 columns. Suppose, we want to remove 2nd and 4th row, then we can substract them from mydata –

mydata = mydata[-c(2, 4), ]
mydata

  A B C
1 1 a Q
3 3 c E

You may also use the boolean list in order to reject or keep any row. For example, in our case we want to remove 2nd and 4th row, so we can also do this –

row_to_keep = c(TRUE, FALSE, TRUE, FALSE)
mydata = mydata[row_to_keep, ]
mydata

  A B C
1 1 a Q
3 3 c E

In our boolean array, we kept 1st and 3rd values to be True and others as False. We we pass this array to our dataframe, all the False value indexes will be removed. You can use the negative operator (!) to reverse the effect –

row_to_keep = c(TRUE, FALSE, TRUE, FALSE)
mydata = mydata[!row_to_keep, ]
mydata

  A B C
1 2 b W
3 4 d R

Β Β Β Β Tweet this to help others

Live Demo

Demo might not work in private window (incognito)

R

Tagged in:

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles