在向量中使用 group_by ALL 记录过滤 tibble(没有多个 ANY 语句)

filter tibble with group_by ALL records in vector (without multiple ANY statements)

提问人:T. BruceLee 提问时间:12/20/2022 更新时间:12/20/2022 访问量:23

问:

我只是想知道是否可以根据向量作为输入来选择(过滤)数据帧/tibble 中的整个组。

这是我的示例(小)数据集:

# load packages
require(tidyverse)

# make example data
data1 <- tibble(a = "groep", b = c(1,2,3)) 
data2 <- tibble( a = "groep2", b = c(1,2))
data3 <- tibble( a = "groep3", b = c(1,2,3,4))
data4 <- tibble( a = "groep4", b = c(2,3,5))

#combine example data
example <- bind_rows(data1, data2, data3, data4)

现在我想提取包含数字 1、2 和 3 的组。又名 data1data3。 我想用一个函数来做到这一点。group_by

我可以这样做:

example %>% group_by(a) %>% filter(any(b ==1) & any(b==2) & any(b==3)) %>% ungroup

我对输出感到满意,尽管我想知道是否有不那么繁琐的方法? 这些只是这个代码块中的 3 个。但是,如果有呢any

vec <- c(1,2,3)

是否可以使用此向量“vec”生成相同的输出?

R 筛选器 分组划分 切片

评论


答:

1赞 akrun 12/20/2022 #1

我们可以与%in%all

library(dplyr)
example %>%
   group_by(a) %>%
   filter(all(vec %in% b)) %>%
   ungroup

-输出

# A tibble: 7 × 2
  a          b
  <chr>  <dbl>
1 groep      1
2 groep      2
3 groep      3
4 groep3     1
5 groep3     2
6 groep3     3
7 groep3     4

评论

0赞 akrun 12/20/2022
@T.BruceLee 这将为所有组返回 TRUE,因为 和 是相同的。相反,您希望与“b”中的列值进行比较vecc(1, 2, 3)
0赞 T. BruceLee 12/20/2022
我删除了我的评论,因为我打错了字,所以我的评论没有帮助。这就是我的意思:我之前尝试过“all( )”,但事实证明“all(vec %in% b)”与“all(b %in% vec)”不同:)