Remove Rows From Data Frame where a Row matches a String

RDataframe

R Problem Overview


I do I remove all rows in a dataframe where a certain row meets a string match criteria?

For example:

A,B,C
4,3,Foo
2,3,Bar
7,5,Zap

How would I return a dataframe that excludes all rows where C = Foo:

A,B,C
2,3,Bar
7,5,Zap

R Solutions


Solution 1 - R

Just use the == with the negation symbol (!). If dtfm is the name of your data.frame:

dtfm[!dtfm$C == "Foo", ]

Or, to move the negation in the comparison:

dtfm[dtfm$C != "Foo", ]

Or, even shorter using subset():

subset(dtfm, C!="Foo")

Solution 2 - R

You can use the dplyr package to easily remove those particular rows.

library(dplyr)
df <- filter(df, C != "Foo")

Solution 3 - R

I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --

df <- df [(!(df$A=="no") & !(df$A=="unknown")),]

Solution 4 - R

if you wish to using dplyr, for to remove row "Foo":

df %>%
 filter(!C=="Foo")

Solution 5 - R

I know this has been answered but here is another option:

library (dplyr)
df %>% filter(!c=="foo)
OR
df[!df$c=="foo", ]

Solution 6 - R

If your exclusion conditions are stored in another data frame you could use rows_delete:

library(dplyr)

removal_df <- data.frame(C = "Foo")

df %>% 
  rows_delete(removal_df, by = "C")

  A B   C
1 2 3 Bar
2 7 5 Zap

This is also handy if you have multiple exclusion conditions so you do not have to write out a long filter statement.

Note: rows_delete is only available if you have dplyr >= 1.0.0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle BrandtView Question on Stackoverflow
Solution 1 - RLuciano SelzerView Answer on Stackoverflow
Solution 2 - RPranesh KrishnamurthyView Answer on Stackoverflow
Solution 3 - RPratik HonraoView Answer on Stackoverflow
Solution 4 - Rwesleysc352View Answer on Stackoverflow
Solution 5 - RHumza IftikharView Answer on Stackoverflow
Solution 6 - RLMcView Answer on Stackoverflow