tidyr - unique way to get combinations (using tidyverse only)

…衆ロ難τιáo~ 提交于 2019-12-05 21:45:41

wish there was a better way, but I usually use this...

library(tidyverse)

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

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

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

Something like this?

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!