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"
如果我还有与b-a,c-a ... d-c的逆组合,我应该如何编写代码。总共12种组合。
答案 0 :(得分:5)
您可以使用基础R中的expand.grid
来获取向量的所有可能组合(即16种组合),然后使用subset
(或[.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
答案 1 :(得分:4)
包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"
答案 2 :(得分:1)
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