Home > Enterprise >  Returning all rows that don't contain a certain value
Returning all rows that don't contain a certain value

Time:07-23

Example data frame:

> df <- data.frame(A = c('a', 'b', 'c'), B = c('c','d','e'))
> df
  A B
1 a c
2 b d
3 c e

The following returns all rows in which any value is "c"

> df %>% filter_all(any_vars(. == "c"))
  A B
1 a c
2 c e

How do I return the inverse of this, all rows in which no value is ever "c"? In this example, that would be row 2 only. Tidyverse solutions preferred, thanks.

EDIT: To be clear, I am asking about exact matching, I don't care if a value contains a "c", just if the value is exactly "c".

CodePudding user response:

dplyr

FYI, filter_all has been superseded by the use of if_any or if_all.

df %>%
  filter(if_all(everything(), ~ . != "c"))
#   A B
# 1 b d

CodePudding user response:

Do you have to use dplyr?

df[rowSums(df == 'c') == 0, ]
#  A B
#2 b d

Adding OP's comments into answer

This works for me, thank you. My original issue was that any row with a "c" somewhere also had an NA somewhere else, so the adapted solution is

df[rowSums(df == 'c', na.rm = TRUE) == 0, ]

Honestly this is more readable than dplyr syntax. But as I asked for a dplyr solution, I accepted another answer.

CodePudding user response:

df %>% filter_all(all_vars(. != "c"))

  A B
1 b d
  • Related