Advertisement
Guest User

Untitled

a guest
May 24th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. # vector
  2. x = c('1','2','3')
  3.  
  4. # 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
  5.  
  6. # two-way is easy
  7. get_all_combs <- function(x){
  8. return(expand.grid(x,x) %>%
  9. filter(Var1 != Var2) %>%
  10. unite(., 'y', everything(), sep = '') %>%
  11. pull(y))
  12. }
  13.  
  14. get_all_combs(x)
  15.  
  16. # becomes much harder with three way
  17.  
  18.  
  19. get_all_combs <- function(x, vec_len = 2){
  20. # set command
  21. return(expand.grid(rep(list(x), vec_len)) %>%
  22. filter(apply(., 1, function(x)length(unique(x))) == vec_len) %>%
  23. unite(., 'y', everything(), sep = '') %>%
  24. pull(y))
  25. }
  26.  
  27. # bit gnarly but gets there - the apply is very stressful but not sure how else to do it
  28. get_all_combs(x, vec_len = 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement