Warm tip: This article is reproduced from stackoverflow.com, please click
r select

filter rows if any of the two columns have the specified value

发布于 2020-03-29 12:46:00

I have a data frame with 7 columns say a1, a2,...., a7. a1 and a2 have numeric values while the rest have strings (athlete names in this case). I want to select rows that "John" and "Peter" appear together in any two of the columns (a3 to a7). In the example below, I want to select only row 2 and 4.

Example

enter image description here .

I've searched all over the internet, but can't find any direction. Does anyone have any idea? Is it doable? thank you!

Questioner
Rockaell
Viewed
57
Steffen Eichhorn 2020-01-31 15:11
library(tidyverse)
df <- data.frame(
  a1 = c(14,23,24,6,4),
  a2 = c(5,67,4,57,54),
  a3 = c("Paul", "John", "Mike", "Peter", "John"),
  a4 = c("John", "Phil", "Peter", "John", "Luke"),
  a5 = c("Dave", "Peter", "Nick", "Paul", "Phil"),
  a6 = c("Adrian", "Keim", "Rick", "Luke", "Mike"),
  a7 = c("Rick", "Luke", "Adrian", "Rick", "Dave")
)

df %>%
  filter_all(
    any_vars(. == "Peter")
  ) %>%
  filter_all(
    any_vars(. == "John")
  )