x <- letters[1:4]
x
# [1] "a" "b" "c" "d"
t(combn(x, 2))
# [,1] [,2]
# [1,] "a" "b"
# [2,] "a" "c"
# [3,] "a" "d"
# [4,] "b" "c"
# [5,] "b" "d"
# [6,] "c" "d"
如果我还与 ba、ca...dc 进行逆向组合,我应该如何编写代码。一共12种组合。
您可以使用expand.grid
from base R 来获取向量的所有可能组合(即 16 个组合),然后使用subset
(or [.data.frame
) 以便两列中的值在一行中永远不会相等(导致预期的 12 个组合):
x <- letters[1:4]
subset(expand.grid(rep(list(x),2)), Var1 != Var2)
# Var1 Var2
#2 b a
#3 c a
#4 d a
#5 a b
#7 c b
#8 d b
#9 a c
#10 b c
#12 d c
#13 a d
#14 b d
#15 c d
data.table
的交叉连接 ( CJ
) 功能的替代方案:
libraray(data.table)
CJ(x, x)[V1 != V2]
# V1 V2
# 1: a b
# 2: a c
# 3: a d
# 4: b a
# 5: b c
# 6: b d
# 7: c a
# 8: c b
# 9: c d
#10: d a
#11: d b
#12: d c
包gtools
有一个permutations
功能。
x <- letters[1:4]
library(gtools)
permutations(length(x), 2, x, repeats = FALSE)
# [,1] [,2]
# [1,] "a" "b"
# [2,] "a" "c"
# [3,] "a" "d"
# [4,] "b" "a"
# [5,] "b" "c"
# [6,] "b" "d"
# [7,] "c" "a"
# [8,] "c" "b"
# [9,] "c" "d"
# [10,] "d" "a"
# [11,] "d" "b"
# [12,] "d" "c"
另一种选择dplyr/tidyr
library(dplyr)
library(tidyr)
data_frame(x1=x,x2=x) %>%
expand(x1, x2) %>%
filter(x1!=x2)
# x1 x2
# (chr) (chr)
#1 a b
#2 a c
#3 a d
#4 b a
#5 b c
#6 b d
#7 c a
#8 c b
#9 c d
#10 d a
#11 d b
#12 d c