【问题标题】:tidyr - unique way to get combinations (using tidyverse only)tidyr - 获取组合的独特方式(仅使用 tidyverse)
【发布时间】:2017-09-29 14:49:31
【问题描述】:

我想使用tidyverse(理想情况下)获取数据帧的唯一字符串列的所有唯一成对组合。

这是一个虚拟示例:

library(tidyverse)

a <- letters[1:3] %>% 
        tibble::as_tibble()
a
#> # A tibble: 3 x 1
#>   value
#>   <chr>
#> 1     a
#> 2     b
#> 3     c

tidyr::crossing(a, a) %>% 
    magrittr::set_colnames(c("words1", "words2"))
#> # A tibble: 9 x 2
#>   words1 words2
#>    <chr>  <chr>
#> 1      a      a
#> 2      a      b
#> 3      a      c
#> 4      b      a
#> 5      b      b
#> 6      b      c
#> 7      c      a
#> 8      c      b
#> 9      c      c

有没有办法在这里删除“重复”组合。在这个例子中,输出如下:

# A tibble: 9 x 2
#>   words1 words2
#>    <chr>  <chr>
#> 1      a      b
#> 2      a      c
#> 3      b      c

我希望有一个很好的 purrr::mapfilter 方法来完成上述操作。

编辑:有与此类似的问题,例如here,由@Sotos 标记。在这里,我专门寻找 tidyverse (purrr, dplyr) 方法来完成我设置的管道。其他答案使用我不想包含为依赖项的各种其他包。

【问题讨论】:

  • @Sotos - 我已经读过这个问题了。我特别要求这个问题使用 tidyverse 包,特别是 purrr::map 解决方案。请删除重复标志

标签: r tidyr tidyverse


【解决方案1】:

希望有更好的方法,但我通常使用这个...

library(tidyverse)

df <- tibble(value = letters[1:3])

df %>% 
  expand(value, value1 = value) %>% 
  filter(value < value1)

# # A tibble: 3 x 2
#   value value1
#   <chr> <chr> 
# 1 a     b     
# 2 a     c     
# 3 b     c  

【讨论】:

  • 我正在尝试解决同样的问题,但现在遇到的问题Error: Column name value`不能重复。`当我使用你的解决方案时:-(
  • 已编辑以使用当前的 tidyverse 版本(tidyverse 最近实施了新的/更严格的列名检查)
【解决方案2】:

这样的?

tidyr::crossing(a, a) %>% 
  magrittr::set_colnames(c("words1", "words2")) %>%
  rowwise() %>%
  mutate(words1 = sort(c(words1, words2))[1],       # sort order of words for each row
         words2 = sort(c(words1, words2))[2]) %>%
  filter(words1 != words2) %>%                      # remove word combinations with itself
  unique()                                          # remove duplicates

# A tibble: 3 x 2
  words1 words2
   <chr>  <chr>
1      a      b
2      a      c
3      b      c

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    相关资源
    最近更新 更多