Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: all possible combinations from a vector of elements with 2 possible conditions (+/-)

I have a vector of elements named markers of the form:

markers <- LETTERS[1:5]

Each element in markers is of Boolean type with two possible conditions + and -. I would like a fast an efficient way to obtain all possible combinations, so that the two conditions are considered (a marker with cannot be paired with itself even if the condition is different).

The result would ideally be just a character vector or a list, where its elements are the marker combinations separated by /.

The elements for this example with five letters should be:

A-/B-/C-/D-/E-
A-/B+/C-/D-/E-
A-/B-/C+/D-/E-
A-/B-/C-/D+/E-
A-/B-/C-/D-/E+
A-/B+/C+/D-/E-
A-/B+/C-/D+/E-
A-/B+/C-/D-/E+
A-/B+/C+/D+/E-
A-/B+/C+/D-/E+
A-/B+/C+/D+/E+
A+/B-/C-/D-/E-
A+/B+/C-/D-/E-
A+/B-/C+/D-/E-
A+/B-/C-/D+/E-
A+/B-/C-/D-/E+
A+/B+/C+/D-/E-
A+/B+/C-/D+/E-
A+/B+/C-/D-/E+
A+/B+/C+/D+/E-
A+/B+/C+/D-/E+
A+/B+/C+/D+/E+
...

Not sure if I'm missing any combination, but you get the idea... I've been trying with expand.grid and combn but I don't seem to get it right. Any help appreciated!

Thanks!

like image 939
DaniCee Avatar asked Sep 24 '20 06:09

DaniCee


1 Answers

markers <- LETTERS[1:5]

test <- expand.grid(lapply(seq(markers), function(x) c("+","-")),stringsAsFactors=FALSE)

> test
   Var1 Var2 Var3 Var4 Var5
1     +    +    +    +    +
2     -    +    +    +    +
3     +    -    +    +    +
4     -    -    +    +    +
 ....


apply(test,1,function(x){paste0(markers,x,collapse = "/")}) 


 [1] "A+/B+/C+/D+/E+" "A-/B+/C+/D+/E+" "A+/B-/C+/D+/E+" "A-/B-/C+/D+/E+" "A+/B+/C-/D+/E+" "A-/B+/C-/D+/E+" "A+/B-/C-/D+/E+"
 [8] "A-/B-/C-/D+/E+" "A+/B+/C+/D-/E+" "A-/B+/C+/D-/E+" "A+/B-/C+/D-/E+" "A-/B-/C+/D-/E+" "A+/B+/C-/D-/E+" "A-/B+/C-/D-/E+"
[15] "A+/B-/C-/D-/E+" "A-/B-/C-/D-/E+" "A+/B+/C+/D+/E-" "A-/B+/C+/D+/E-" "A+/B-/C+/D+/E-" "A-/B-/C+/D+/E-" "A+/B+/C-/D+/E-"
[22] "A-/B+/C-/D+/E-" "A+/B-/C-/D+/E-" "A-/B-/C-/D+/E-" "A+/B+/C+/D-/E-" "A-/B+/C+/D-/E-" "A+/B-/C+/D-/E-" "A-/B-/C+/D-/E-"
[29] "A+/B+/C-/D-/E-" "A-/B+/C-/D-/E-" "A+/B-/C-/D-/E-" "A-/B-/C-/D-/E-"
like image 177
denis Avatar answered Oct 19 '22 15:10

denis