独特的字符串组合 [英] Unique string combinations

查看:56
本文介绍了独特的字符串组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含某些单词的向量

I have a vector which contains certain words

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

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

现在我要创建一个新变量 colorsCombined ,其中存在原始矢量以及这些单词的所有可能组合。

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"

我认为YellowBlue与BlueYellow相同。

I consider YellowBlue to be the same as BlueYellow.

我该怎么做?

推荐答案

一种选择是在 lapply中运行 combn 函数循环。您可以将其定义为自己的函数

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"

说明(每个请求)

基本上,OP希望得到所有可能组合的向量(不是排列)取决于输入向量的长度。因此,我们应该在 k <-:1:length(x)上运行 combn 函数,并为每 k
因此,当 k == 1 时,它只是原始向量,因此我们可以跳过该部分,而仅使用 c连接原始向量。其余生成的组合将返回具有不同长度的向量列表(出于明显的原因,其顺序为降序),因此我们需要在<$ c中使用 recursive = TRUE $ c> c 函数,以模仿 unlist 的行为并将结果组合到单个向量中。

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.

这篇关于独特的字符串组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆