user9292
user9292

Reputation: 1145

Generate all combinations (and their sum) of a vector of characters in R

Suppose that I have a vector of length n and I need to generate all possible combinations and their sums. For example:

If n=3, we have:

myVec <- c("a", "b", "c")

Output = 
"a"
"b"
"c"
"a+b"
"a+c"
"b+c"
"a+b+c"

Note that we consider that a+b = b+a, so only need to keep one.

Another example if n=4,

myVec <- c("a", "b", "c", "d")

Output:
"a"
"b"
"c"
"d"
"a+b"
"a+c"
"a+d"
"b+c"
"b+d"
"c+d"
"a+b+c"
"a+c+d"
"b+c+d"
"a+b+c+d"

Upvotes: 1

Views: 47

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

We can use sapply with varying length in combn and use paste as function to apply.

sapply(seq_along(myVec), function(n) combn(myVec, n, paste, collapse = "+"))

#[[1]]
#[1] "a" "b" "c"

#[[2]]
#[1] "a+b" "a+c" "b+c"

#[[3]]
#[1] "a+b+c"


myVec <- c("a", "b", "c", "d")
sapply(seq_along(myVec), function(n) combn(myVec, n, paste, collapse = "+"))

#[[1]]
#[1] "a" "b" "c" "d"

#[[2]]
#[1] "a+b" "a+c" "a+d" "b+c" "b+d" "c+d"

#[[3]]
#[1] "a+b+c" "a+b+d" "a+c+d" "b+c+d"

#[[4]]
#[1] "a+b+c+d"

We can unlist if we need output as single vector.

Upvotes: 3

Related Questions