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?
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
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")))
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')))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With