Search code examples
rnadelete-row

Remove multiple rows if condition for one row is met


I have the following dataset:

ID   value
abc    1
abc    NA
abc    2
def    5
def    1 
def    4

I know how to identify the ID of the row that contains a NA . What I want to do is to delete all rows with the ID if one row contains a NA. In this case: One row of abc shows an NA, thus all rows with ID = abc should be removed, so that the dataframe looks like this:

ID   value
def    5
def    1 
def    4

Solution

  • You can use the negated ! %in% of ID which have an NA to delete all rows with the ID if one row contains a NA.

    x[!x$ID %in% unique(x$ID[is.na(x$value)]),]
    #   ID value
    #4 def     5
    #5 def     1
    #6 def     4