r - Unique string combinations -


i have vector contains words

colors<-c("yellow","blue","red")  > colors [1] "yellow" "blue"   "red"  

now want create new variable, colorscombined, in original vector present , possible combinations of words.

> colorscombined [1] "yellow", "blue", "red", "yellowblue", "yellowred", "bluered", "yellowbluered" 

i consider yellowblue same blueyellow.

how do this?

one option run combn function in lapply loop. can define own function

allcombs <- function(x) c(x, lapply(seq_along(x)[-1l],                               function(y) combn(x, y, paste0, collapse = "")),                              recursive = true)  allcombs(colors) ## [1] "yellow" "blue" "red" "yellowblue" "yellowred" "bluered" "yellowbluered" 

explanation (per request)

basically op wants vector of possible combinations (not permutations) depending on length of input vector. thus, should run combn function on k <- 1:length(x) , generate combinations every k. when k == 1, it's original vector, can skip part , concatenate original vector using c. rest of generated combinations return list of vectors different lengths (in descending order obvious reasons), need use recursive = true within c function in order mimic behaviour of unlist , combine results single vector.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -