Home > Blockchain >  Only keep rows where at least one of the 3 columns equals a given value
Only keep rows where at least one of the 3 columns equals a given value

Time:11-01

I have a dataframe in which I want to filter to rows where at least one of 3 different columns has value "D"

Sample df:

identifier def abc ghi
1 D C A
2 A D D
3 B C A
4 A D A

I want my output to be:

identifier def abc ghi
1 D C A
2 A D D
4 A D A

I would like to use dplyr filter() but couldn't find how to filter to exactly what I need

CodePudding user response:

With if_any:

library(dplyr)
dat %>%
  filter(if_any(-identifier, ~ .x == "D"))

  identifier def abc ghi
1          1   D   C   A
2          2   A   D   D
3          4   A   D   A

CodePudding user response:

Using base R

subset(df1,  rowSums(df1[-1] == "D") > 0)

-output

   identifier def abc ghi
1          1   D   C   A
2          2   A   D   D
4          4   A   D   A
  • Related