Q:

dplyr filter whole dataframe on subset

I am trying to filter a data set by removing a variable, but only when conditions are met on a subset of the data. Here's a toy example.
Using mtcars, I would like to filter based on cyl. I don't know what the condition to filter out is yet, but I do know the conditions on producing the values in cyl. For example, I want to remove any car with x cylinders. I don't yet know what x is. I DO know that x is whatever cylinders meet the condition mpg < 17 & disp < 300. It happens to be that the only value of cyl under this condition is "8". Therefore, the end result is filtering the entire data frame on cyl != 8. I imagine the solution would look something like the following, which didn't work:
library(tidyverse)
mtcars %>% 
  as_tibble(rownames = "cars") %>% 
  filter(cyl %in% unique(mpg < 17 & disp < 300))

The desired result is mtcars without any 8-cylinder cars.

A:

We use the logical condition to subset the 'cyl' and then wrap unique on it and use the condition %in%
library(dplyr)
mtcars %>%
   as_tibble(rownames = "cars") %>%
   filter(!cyl %in% unique(cyl[mpg < 17 & disp < 300]))
# A tibble: 18 x 12
#   cars             mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#   <chr>          <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 Mazda RX4       21       6 160     110  3.9   2.62  16.5     0     1     4     4
# 2 Mazda RX4 Wag   21       6 160     110  3.9   2.88  17.0     0     1     4     4
# 3 Datsun 710      22.8     4 108      93  3.85  2.32  18.6     1     1     4     1
# 4 Hornet 4 Drive  21.4     6 258     110  3.08  3.22  19.4     1     0     3     1
# 5 Valiant         18.1     6 225     105  2.76  3.46  20.2     1     0     3     1
# 6 Merc 240D       24.4     4 147.     62  3.69  3.19  20       1     0     4     2
# 7 Merc 230        22.8     4 141.     95  3.92  3.15  22.9     1     0     4     2
# 8 Merc 280        19.2     6 168.    123  3.92  3.44  18.3     1     0     4     4
# 9 Merc 280C       17.8     6 168.    123  3.92  3.44  18.9     1     0     4     4
#10 Fiat 128        32.4     4  78.7    66  4.08  2.2   19.5     1     1     4     1
#11 Honda Civic     30.4     4  75.7    52  4.93  1.62  18.5     1     1     4     2
#12 Toyota Corolla  33.9     4  71.1    65  4.22  1.84  19.9     1     1     4     1
#13 Toyota Corona   21.5     4 120.     97  3.7   2.46  20.0     1     0     3     1
#14 Fiat X1-9       27.3     4  79      66  4.08  1.94  18.9     1     1     4     1
#15 Porsche 914-2   26       4 120.     91  4.43  2.14  16.7     0     1     5     2
#16 Lotus Europa    30.4     4  95.1   113  3.77  1.51  16.9     1     1     5     2
#17 Ferrari Dino    19.7     6 145     175  3.62  2.77  15.5     0     1     5     6
#18 Volvo 142E      21.4     4 121     109  4.11  2.78  18.6     1     1     4     2

