获取不同的单词组合 [英] Get different combinations of words

查看:24
本文介绍了获取不同的单词组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串 ch 并且我想获得一个特定的输出 out.请参阅以下示例.

I have a string ch and I want to get a specific output out. Please see below examples.

ch <- "A B"
out <- "A B AB"

ch <- "A B C"
out <- "A B C AB BC AC ABC"

ch <- "A B C D"
out <- "A B C D AB BC CD AC AD BD ABC ABD ACD BCD ABCD"

基本上,我想获得字符串中所有单词的所有可能向前组合,如上所述.

Basically I want to get all possible going forward combinations of all words present in a string as explained above.

如何在 R 中以最简单的方式实现这一目标?

How do I achieve this in the easiest way in R?

我尝试了以下操作.但它似乎给出了所有可能的组合,在这种情况下很难过滤掉我需要的情况.

I tried following. But it seems to be giving all possible combinations in which case it will get difficult to filter out the cases I need.

e <- c("A", "B", "C")
> r <- expand.grid(e, e, e)
> r
   Var1 Var2 Var3
1     A    A    A
2     B    A    A
3     C    A    A
4     A    B    A
5     B    B    A
6     C    B    A
7     A    C    A
8     B    C    A
9     C    C    A
10    A    A    B
11    B    A    B
12    C    A    B
13    A    B    B
14    B    B    B
15    C    B    B
16    A    C    B
17    B    C    B
18    C    C    B
19    A    A    C
20    B    A    C
21    C    A    C
22    A    B    C
23    B    B    C
24    C    B    C
25    A    C    C
26    B    C    C
27    C    C    C

推荐答案

一种选择是将字符串按空格split (strsplit(str1, ' ')), 按'v1'长度的序列循环,得到'v1'的combn作为序列,粘贴输出列中的元素(apply(..., 2, ...)), unlistpaste .我们可以创建一个执行这些操作的函数 ('f1') 并将其用于多个字符串.

One option would be to split the string by space (strsplit(str1, ' ')), loop by the sequence of length of 'v1', get the combn of 'v1' for sequence, paste the elements in output columns (apply(..., 2, ...)), unlist and paste again. We can create a function ('f1') that does these and use it for multiple strings.

f1 <- function(str1){
  v1 <- strsplit(str1, ' ')[[1]]
  paste(unlist(sapply(seq(length(v1)), function(i)
        apply(combn(v1, i), 2, paste, collapse=""))), collapse= ' ')
  }

ch <- "A B"
f1(ch)
#[1] "A B AB"

ch <- "A B C"    
f1(ch)
#[1] "A B C AB AC BC ABC"

ch <- "A B C D"
f1(ch)
#[1] "A B C D AB AC AD BC BD CD ABC ABD ACD BCD ABCD"

这篇关于获取不同的单词组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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