I have a data frame named "mydata" that looks like this this:
A B C D
1. 5 4 4 4
2. 5 4 4 4
3. 5 4 4 4
4. 5 4 4 4
5. 5 4 4 4
6. 5 4 4 4
7. 5 4 4 4
I'd like to delete row 2,4,6. For example, like this:
A B C D
1. 5 4 4 4
3. 5 4 4 4
5. 5 4 4 4
7. 5 4 4 4
Here's a quick and dirty function to remove a row by index.
It's main flaw is it the row_index argument doesn't follow the R pattern of being a vector of values. There may be other problems as I only spent a couple of minutes writing and testing it, and have only started using R in the last few weeks. Any comments and improvements on this would be very welcome!
The key idea is you form a set of the rows you want to remove, and keep the complement of that set.
In R, the complement of a set is given by the '-' operator.
So, assuming the
data.frame
is calledmyData
:Of course, don't forget to "reassign"
myData
if you wanted to drop those rows entirely---otherwise, R just prints the results.Delete Dan from employee.data - No need to manage a new data.frame.
By simplified sequence :
By sequence :
By negative sequence :
Or if you want to subset by selecting odd numbers:
Or if you want to subset by selecting odd numbers, version 2:
Or if you want to subset by filtering even numbers out:
Or if you want to subset by filtering even numbers out, version 2:
You can also work with a so called boolean vector, aka
logical
:Note that the
!
operator acts as a NOT, i.e.!TRUE == FALSE
:This seems a bit cumbersome in comparison to @mrwab's answer (+1 btw :)), but a logical vector can be generated on the fly, e.g. where a column value exceeds a certain value:
You can transform a boolean vector to a vector of indices:
Finally, a very neat trick is that you can use this kind of subsetting not only for extraction, but also for assignment:
where column
A
is assignedNA
(not a number) whereA
exceeds 4.Create id column in your data frame or use any column name to identify the row. Using index is not fair to delete.
Use
subset
function to create new frame.