首页 > 解决方案 > 删除数据框中变量的镜像组合

问题描述

我正在寻找两个变量的每个独特组合:

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值是否在id1orid2中,因此以下内容与输出一样可以接受:

# A tibble: 3 x 2
    id1   id2
  <int> <int>
1     1     2
2     1     3
3     2     3

标签: rpurrr

解决方案


丹的回答的 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

推荐阅读