简体   繁体   中英

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM