Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

r - Unique string combinations

I have a vector which contains certain words

colors<-c("Yellow","Blue","Red")

> colors
[1] "Yellow" "Blue"   "Red" 

Now I want to create a new variable, colorsCombined, in which the original vector is present and also all possible combinations of those words.

> colorsCombined
[1] "Yellow", "Blue", "Red", "YellowBlue", "YellowRed", "BlueRed", "YellowBlueRed"

I consider YellowBlue to be the same as BlueYellow.

How do I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One option is to run the combn function in a lapply loop. You can define it as your 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 a vector of all possible combinations (not permutations) depending on the length of the input vector. Thus, we should run the combn function over k <- 1:length(x) and generate all combinations for every k. So when k == 1, it's just the original vector, so we can skip that part and just concatenate the original vector using c. The rest of the generated combinations return a list of vectors with different lengths (in a descending order for obvious reasons), thus we need to use recursive = TRUE within the c function in order to mimic the behaviour of unlist and combine the results into a single vector.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...