tidyr - 获得组合的独特方式(仅使用 tidyverse) [英] tidyr - unique way to get combinations (using tidyverse only)
问题描述
我想使用 tidyverse
(理想情况下)获取数据帧的唯一字符串列的所有唯一成对组合.
I wanted to get all unique pairwise combinations of a unique string column of a dataframe using the tidyverse
(ideally).
这是一个虚拟示例:
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
有没有办法在这里删除重复"组合.在这个例子中,输出如下:
Is there a way to remove 'duplicate' combinations here. That is have the output be the following in this example:
# A tibble: 9 x 2
#> words1 words2
#> <chr> <chr>
#> 1 a b
#> 2 a c
#> 3 b c
我希望有一个很好的 purrr::map
或 filter
方法来完成上述操作.
I was hoping there would be a nice purrr::map
or filter
approach to pipe into to complete the above.
有与此类似的问题,例如此处,由@Sotos 标记.在这里,我专门寻找 tidyverse (purrr
, dplyr
) 方法来完成我设置的管道.其他答案使用了我不想作为依赖项包含在内的各种其他包.
There are similar questions to this one e.g. here, marked by @Sotos. Here I am specifically looking for tidyverse (purrr
, dplyr
) ways to complete the pipeline I have setup. The other answers use various other packages that I do not want to include as dependencies.
推荐答案
希望有更好的方法,但我通常使用这个...
wish there was a better way, but I usually use this...
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
这篇关于tidyr - 获得组合的独特方式(仅使用 tidyverse)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!