Reputation: 683
I'm using the tidyr crossing() function and am able to build a df with each possible permutation of the same names but wish to retain only unique combinations instead of the permutations it seems to create:
names_obj <- c("n1", "n2","n3", "n4","n5","n6","n7","n8","n9","n10","n11","n12")
crossing(n1 = names_obj, n2 = names_obj) %>%
filter(n1 != n2)
If you run this code you'll see that in row 1 (n1 = n1, n2 = n10) is the same combo of names as row 12 (n1 = n10, n2 = n1)
How might I adjust this to only keep one of these combos? I don't care which one it is.
Upvotes: 0
Views: 71
Reputation: 25323
Another possible solution, however not as succinct as @onyambu's one:
library(tidyverse)
crossing(n1 = names_obj, n2 = names_obj) %>%
filter(n1 != n2) %>%
filter(!duplicated(str_c(pmax(n1, n2), pmin(n1, n2))))
#> # A tibble: 66 × 2
#> n1 n2
#> <chr> <chr>
#> 1 n1 n10
#> 2 n1 n11
#> 3 n1 n12
#> 4 n1 n2
#> 5 n1 n3
#> 6 n1 n4
#> 7 n1 n5
#> 8 n1 n6
#> 9 n1 n7
#> 10 n1 n8
#> # … with 56 more rows
Upvotes: 1