过滤具有许多条件的数据框 R

filter a dataframe with many conditions R

我有一个带有产品编号的大型数据框(名为 P),我想用另一个数字数据框(名为 Numb)过滤该数据框。

Productnumb Price Store 
1000           2     A
1001           9     D
1002           1     B
1003           3     A
...
9999           8     D

麻木的数据帧也可以是一个列表。下面的麻木数据框:

Good_products
1003
1009
...
9999

预期输出

Good_products Price Store
1003             3   A
1009            11   G
...
9999             8   D

我试过了 P <- P %>% filter(Productnumb == Numb$Good_products) 我知道它适用于 1 或 2 个条件,但我必须过滤很多条件,所以是否有可能过滤大量 list/dataframes 的数字(作为条件)?

semi_join 可能是一种通过优质产品列表“过滤”的快速简便的方法:

library(dplyr)

# Some simulated data
P <- tibble(
  ProductNum = 1000:1999,
  Price = sample(1:20, 1000, replace = TRUE),
  Store = sample(LETTERS, 1000, replace = TRUE)
)

# A sample of "good products"
Numb <- tibble(GoodProducts = sample(P$ProductNum, 400))


P %>% 
  semi_join(Numb, by = c("ProductNum" = "GoodProducts"))

#> # A tibble: 400 x 3
#>    ProductNum Price Store
#>         <int> <int> <chr>
#>  1       1001    14 H    
#>  2       1004     9 Q    
#>  3       1008     6 B    
#>  4       1014    17 Z    
#>  5       1018    18 Q    
#>  6       1020     3 P    
#>  7       1026    14 G    
#>  8       1031    16 L    
#>  9       1034     2 W    
#> 10       1037    14 P    
#> # ... with 390 more rows

其他步骤在某种程度上取决于您要如何过滤。作为下一步,您可以通过管道传输过滤器(例如 Price < 10),或者进一步执行 semi_join。诚然,这只是执行您上面提到的操作的另一种方式,因此不确定它是否能解决您的问题。向 filter 添加大量条件也应该可以正常工作。

reprex package (v2.0.1)

于 2022-04-20 创建