Skip to content

Instantly share code, notes, and snippets.

@padpadpadpad
Last active May 14, 2019 12:28
Show Gist options
  • Save padpadpadpad/49f6d0b8dc9472388358da383f870a94 to your computer and use it in GitHub Desktop.
Save padpadpadpad/49f6d0b8dc9472388358da383f870a94 to your computer and use it in GitHub Desktop.
get all combinations of a vector of letters
# 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