R:通过多对多映射根据另一列过滤一列

发布于 2025-01-20 22:01:58 字数 551 浏览 2 评论 0原文

我有一个带有ID列和项目列的数据集。 ID映射到一个或多个项目。该数据集对映射到ID的每个项目都有一行。我想返回包含my_items的ID。物品的顺序无关紧要。我下面有一个玩具示例。

ID <- c(1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5, 5)
item <- c("a", "b", "c", "a", "b", "c", "d", "a", "b", "d", "b", "a", "c")
df <- data.frame(cbind(ID, item))
df

my_items <- c("a", "b", "c")

我的预期输出仅包括项目ID 1和5。

I have a dataset with an ID column and an item column. An ID is mapped to one or more items. The dataset has a row for each item mapped to an ID. I want to return IDs that contain my_items. The order of the items does not matter. I have a toy example below.

ID <- c(1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5, 5)
item <- c("a", "b", "c", "a", "b", "c", "d", "a", "b", "d", "b", "a", "c")
df <- data.frame(cbind(ID, item))
df

enter image description here

my_items <- c("a", "b", "c")

My expected output would only include item ID 1 and 5.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

z祗昰~ 2025-01-27 22:01:58
df %>% 
  group_by(ID) %>%
  filter(setequal(item,my_items))

输出

  ID    item 
  <chr> <chr>
1 1     a    
2 1     b    
3 1     c    
4 5     b    
5 5     a    
6 5     c  
df %>% 
  group_by(ID) %>%
  filter(setequal(item,my_items))

Output

  ID    item 
  <chr> <chr>
1 1     a    
2 1     b    
3 1     c    
4 5     b    
5 5     a    
6 5     c  
左岸枫 2025-01-27 22:01:58

我们可以在使用 %in% 创建逻辑向量并按“ID”分组后使用 all,还可以使用 n_distinct

library(dplyr)
df %>% 
   group_by(ID) %>% 
   filter(all(my_items %in% item), n_distinct(item) == 3) %>%
   ungroup

-output创建条件

# A tibble: 6 × 2
     ID item 
  <dbl> <chr>
1     1 a    
2     1 b    
3     1 c    
4     5 b    
5     5 a    
6     5 c   

We can use all after creating a logical vector with %in% and grouping by 'ID' and also create a condition with n_distinct

library(dplyr)
df %>% 
   group_by(ID) %>% 
   filter(all(my_items %in% item), n_distinct(item) == 3) %>%
   ungroup

-output

# A tibble: 6 × 2
     ID item 
  <dbl> <chr>
1     1 a    
2     1 b    
3     1 c    
4     5 b    
5     5 a    
6     5 c   
浅笑依然 2025-01-27 22:01:58

如果我们添加安排,在这种情况下,我们也可以使用相同的

library(dplyr)

  df %>% 
    group_by(ID) %>%
    arrange(item, .by_group = TRUE) %>% 
    filter(identical(item,my_items))
  ID    item 
  <chr> <chr>
1 1     a    
2 1     b    
3 1     c    
4 5     a    
5 5     b    
6 5     c 

If we add arrange, we could also use identical in this case:

library(dplyr)

  df %>% 
    group_by(ID) %>%
    arrange(item, .by_group = TRUE) %>% 
    filter(identical(item,my_items))
  ID    item 
  <chr> <chr>
1 1     a    
2 1     b    
3 1     c    
4 5     a    
5 5     b    
6 5     c 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文