4

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.

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

EDIT:

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
zx8754
  • 52,746
  • 12
  • 114
  • 209
user3664020
  • 2,980
  • 6
  • 24
  • 45

1 Answers1

4

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"
akrun
  • 874,273
  • 37
  • 540
  • 662