Last active
May 14, 2019 12:28
-
-
Save padpadpadpad/49f6d0b8dc9472388358da383f870a94 to your computer and use it in GitHub Desktop.
get all combinations of a vector of letters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# vector | |
x = c('1','2','3') | |
# i want a vector of all combinations of these strings, but i want to be able to say I want all 2 way or three way combs | |
# two-way is easy | |
get_all_combs <- function(x){ | |
return(expand.grid(x,x) %>% | |
filter(Var1 != Var2) %>% | |
unite(., 'y', everything(), sep = '') %>% | |
pull(y)) | |
} | |
get_all_combs(x) | |
# becomes much harder with three way | |
get_all_combs <- function(x, vec_len = 2){ | |
# set command | |
return(expand.grid(rep(list(x), vec_len)) %>% | |
filter(apply(., 1, function(x)length(unique(x))) == vec_len) %>% | |
unite(., 'y', everything(), sep = '') %>% | |
pull(y)) | |
} | |
# bit gnarly but gets there - the apply is very stressful but not sure how else to do it | |
get_all_combs(x, vec_len = 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment