r - 通过公共值组合 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"))
解决方案
根据您的编辑,我将通过首先查找与其他人一起出现在组中的人(称为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中。4
Person 3.1
推荐阅读
- python - 通过 omxplayer 从 Python 进程的内存中播放 MP3,无需写入磁盘
- reactjs - 如何将 MUI 设置分离到外部 js 文件?
- javascript - 在 Javascript 中集成 PHP 变量
- javascript - TypeScript:有没有办法参数化枚举
- node.js - 如何处理在 Nodejs 中多次调用 server.handleUpgrade()?
- excel - 使用 City 在 google 表格中查找县
- python - 如果我有一些 1 位长(如 0x1)和一些 5 位长(如 0x1e4b1)的十六进制数字,我如何编写代码以使它们全部为 8 位?
- php - 链接到 wordpress 主题中的自定义 .php 文件
- javascript - 无法使用 npx babel 运行 pm2?
- amazon-web-services - 无法使用 API 密钥和 COR 查询 AWS API Gateway