Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter rows which has at least one of particular values

I have a data frame like this.

df
    Tour    Order   Machine    Company
[1]    A        D         D          B
[2]    B        B         A          G
[3]    A        E         B          A
[4]    C        B         C          B
[5]    A        G         G          C

I want to get the rows where the three columns Tour, Order Machine contains at least one D E or G.

The result should be:

    Tour    Order   Machine    Company
[1]    A        D         D          B
[3]    A        E         B          A
[5]    A        G         G          C

My attempt:

df %>%
    filter(any(c(Tour, Order, Machine) %in% c('D', 'E', 'G')))

But it doesn't filter correctly(all the rows are returned). Could anybody please help me?

like image 420
Makoto Miyazaki Avatar asked Dec 01 '22 10:12

Makoto Miyazaki


2 Answers

Another tidyverse approach using filter_at

df %>% filter_at(vars(-Company), any_vars(. %in% c("D", "E", "G")))
#  Tour Order Machine Company
#1    A     D       D       B
#2    A     E       B       A
#3    A     G       G       C

Update for dplyr >= 1.0

filter_at and any_vars have been superseded by if_any allowing for the more succinct

df %>% filter(if_any(-Company, `%in%`, c("D", "E", "G")))
like image 144
Maurits Evers Avatar answered Dec 03 '22 23:12

Maurits Evers


Another option:

df[rowSums(sapply(df[-4], '%in%', c('D', 'E', 'G'))) > 0,]

The resut:

  Tour Order Machine Company
1    A     D       D       B
3    A     E       B       A
5    A     G       G       C

With dplyr you should add rowwise():

df %>%
  rowwise() %>% 
  filter(any(c(Tour, Order, Machine) %in% c('D', 'E', 'G')))
like image 24
h3rm4n Avatar answered Dec 03 '22 22:12

h3rm4n