r - tidyr - 获得组合的独特方式(仅使用 tidyverse)

标签 r tidyr tidyverse

我想使用 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 ) 方法来完成我设置的管道。其他答案使用了我不想作为依赖项包含在内的各种其他包。

最佳答案

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

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  

关于r - tidyr - 获得组合的独特方式(仅使用 tidyverse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46491410/

相关文章:

r - geom_point 最小点大小不成比例

r - dplyr 单独返回错误

r - 识别 R 数据框列中的数字或字符序列

用 Tidyverse 替换 R 中的子集

r - 满足给定条件的不同列之间的值差异

r - Cars 包中的多面板散点图

r - 在 Rcpp 中查找向量中所有最大/最小值的索引

r - knitr 与 xelatex 和 tikz : Ghostscript error on minimal example

r - 使用 broom 和 tidyverse 对不同的因变量运行回归

r - 将分隔的字符串拆分为多列并将它们分成行