r - 删除数据框中变量的镜像组合
问题描述
我正在寻找两个变量的每个独特组合:
library(purrr)
cross_df(list(id1 = seq_len(3), id2 = seq_len(3)), .filter = `==`)
# A tibble: 6 x 2
id1 id2
<int> <int>
1 2 1
2 3 1
3 1 2
4 3 2
5 1 3
6 2 3
如何删除镜像组合?也就是说,我只想要上面数据框中的第 1 行和第 3 行之一,只有第 2 和第 5 行之一,以及第 4 和第 6 行之一。我想要的输出类似于:
# A tibble: 3 x 2
id1 id2
<int> <int>
1 2 1
2 3 1
3 3 2
我不在乎某个特定id
值是否在id1
orid2
中,因此以下内容与输出一样可以接受:
# A tibble: 3 x 2
id1 id2
<int> <int>
1 1 2
2 1 3
3 2 3
解决方案
丹的回答的 tidyverse 版本:
cross_df(list(id1 = seq_len(3), id2 = seq_len(3)), .filter = `==`) %>%
mutate(min = pmap_int(., min), max = pmap_int(., max)) %>% # Find the min and max in each row
unite(check, c(min, max), remove = FALSE) %>% # Combine them in a "check" variable
distinct(check, .keep_all = TRUE) %>% # Remove duplicates of the "check" variable
select(id1, id2)
# A tibble: 3 x 2
id1 id2
<int> <int>
1 2 1
2 3 1
3 3 2
推荐阅读
- javascript - 如何在 Vuejs 中的变量中传递方法名称
- maven-3 - 无法让 maven-assembly-plugin 打包测试
- jquery - jQuery 函数仅在我手动将窗口大小调整为移动设备而不是刷新时才有效
- java - 如何将项目输入资源放在 JAR 之外,如 Lib 文件夹
- python - TypeError 输出似乎倒退
- google-apps-script - Google 表格 - 用于将表格导出为仅包含值和格式的 xls 的按钮 - 不是公式
- rust - 如何从更高级别的特征绑定特征返回关联类型?
- r - 如何在不使用移位功能的情况下引用数据表(R)中的上一行?
- android - 如何在反应原生 TVEventHandler 中检测保持和快进事件
- python - 无法将numpy数组重塑为向量