1

I need to remove several rows that meet a condition within a subset.

For instance, using the iris dataset, I would like to remove all the rows in which Sepal.Width = 3.2, but only within setosa

I have tried this: filter(iris, !Species %in% "setosa" & !Sepal.Width==3.2) But his removes all rows containing setosaand all rows in which Sepal.Width==3.2, rather than considering both conditions at the same time (i.e. only remove the rows of the condition within ‘setosa’ and leave the rest

3
  • 1
    General point: if you construct the correct condition, filter and analogues ([] and subset, for example) will all work and no subsetting of subsets is ever needed. In this case you could use !(x & y) as in SabDeM's answer, or the arguably less readable !x | !y Commented Jun 25, 2015 at 19:31
  • 1
    @Frank maybe I am wrong but I am thinking that I've learned such syntax !( <...conditions...> ) here on SO from you (or maybe another power user), because you commented my answer and made me realize the readability of it. As always thank you. Commented Jun 25, 2015 at 19:38
  • @fede_luppi I experienced the same thing with filter(), where it doesn't seem to properly honor boolean AND clauses for multiple criteria. I don't know why this is, and I feel better about myself that someone else has the issue... Anyway the way I solved it was to invert the criteria so it was constructed out of NOT's and OR's rather than an AND. Ugly and counterintuitive, but it worked. Commented Jun 25, 2015 at 22:29

1 Answer 1

4

Here is one way to do so with dplyr:

iris %>% filter(!(Sepal.Width == 3.2 & Species == "setosa")) 

or in base R:

iris[!(iris$Species == "setosa" & iris$Sepal.Width == 3.2), ] 

and last but not least, with subset:

subset(iris, !(Species == "setosa" & Sepal.Width == 3.2)) 

But I think that there are other ways to do such subsetting operations, example, with data table.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.