首页 > 解决方案 > 通过公共值组合 tibble 数据帧

问题描述

阅读评论后,尤其是那些关于如何合并组的评论,我意识到我所问的没有意义。这是我真正想在我的程序中实现的结果:

我有一个如下所示的 tibble 数据框(尽管我的实际数据框更长):

    Group   Person       
     <dbl>    <chr>     
1       1   Person 1.1 
2       2   Person 1.2 
3       2   Person 1.2 
4       3   Person 2.1 
5       4   Person 2.1 
6       4   Person 3.1 
7       5   Person 1.2 
8       5   Person 4.1 
9       6   Person 1.2
10      6   Person 4.2

我希望按组拆分小标题。但是,我有一个组 2,其中只有人员 1.2,但由于人员 1.2 与人员 4.1 在组 5 和人员 4.2 的组 6,我想删除组 2。因此,如果有一个组只有一种类型的人,并且该人与另一个人在一个组中,那么他们自己所在的组应该被删除。

然后数据框将如下所示:

    Group   Person       
    <dbl>    <chr>     
1       1   Person 1.1 
4       3   Person 2.1 
5       4   Person 2.1 
6       4   Person 3.1 
7       5   Person 1.2 
8       5   Person 4.1 
9       6   Person 1.2
10      6   Person 4.2           

上面示例数据框的可重现数据:

structure(list(Group = c(1, 2, 2, 3, 4, 4, 5, 5, 6, 6), Person = 
c("Person 1.1", 
"Person 1.2", "Person 1.2", "Person 2.1", "Person 2.1", "Person 3.1", 
"Person 1 .2", "Person 4.1", "Person 1.2", "Person 4.2")), spec = 
structure(list(
cols = list(Group = structure(list(), class = c("collector_double", 
"collector")), Person = structure(list(), class = 
c("collector_character", 
"collector"))), default = structure(list(), class = 
c("collector_guess", 
"collector")), skip = 1), class = "col_spec"), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

标签: rdataframetibble

解决方案


根据您的编辑,我将通过首先查找与其他人一起出现在组中的人(称为persons_with_others),然后过滤掉该组中的人是persons_with_others.

library(dplyr)
persons_with_others = df %>%
  group_by(Group) %>%
  filter(n_distinct(Person) > 1) %>%
  pull(Person) %>% 
  unique

df %>% 
  group_by(Group) %>%
  filter(!(n_distinct(Person) == 1 & Person %in% persons_with_others))
# # A tibble: 7 x 2
# # Groups:   Group [4]
#   Group Person     
#   <dbl> <chr>      
# 1     1 Person 1.1 
# 2     4 Person 2.1 
# 3     4 Person 3.1 
# 4     5 Person 1 .2
# 5     5 Person 4.1 
# 6     6 Person 1.2 
# 7     6 Person 4.2 

此结果与您想要的输出不同,但我认为它是正确的:Group3被消除,因为它只包含Person 2.1,并且与另一个人 ( ) 一起Person 2.1出现在 Group中。4Person 3.1


推荐阅读