问题描述
我有一个名为 markers
的元素向量,形式为:
I have a vector of elements named markers
of the form:
markers <- LETTERS[1:5]
markers
中的每个元素都是布尔类型,具有两个可能的条件 +
和-
.我想要一种快速有效的方法来获取所有可能的组合,以便考虑这两个条件(即使条件不同,标记也无法与其自身配对).
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+
...
不确定我是否缺少任何组合,但是您明白了...我一直在尝试 expand.grid
和 combn
,但我没有似乎做对了.任何帮助表示赞赏!
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!
谢谢!
推荐答案
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-"
这篇关于R:来自具有2个可能条件(+/-)的元素向量的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!