R - Select 同一列中值的唯一组合

R - Select unique combinations of values from within the same column

假设数据帧结构如下:

ColA  ColB
A     1
A     2
A     4
B     3
B     2
B     4
C     1
C     1
C     1

是否可以select所有A、B、C的组合总和为7(A、B、C各用一次),例如:

ColA  Combination1  Combination2
A     2             4
B     4             2
C     1             1

或者,循环遍历 A、B 和 C 的所有唯一组合以确定它们的总数,然后按列绑定它们会更好吗?如果是这样,假设数据在第一个数据帧的结构中,我将如何遍历 A、B 和 C 的唯一组合?

这是我的建议:

df <- read.table( header =TRUE,
                  text = "ColA  ColB
                          A     1
                          A     2
                          A     4
                          B     3
                          B     2
                          B     4
                          C     1
                          C     1
                          C     1")

X <- tapply(df$ColB, df$ColA, unique)
G <- expand.grid(X)
G <- G[rowSums(G)==7, ]

Combinations <- data.frame(t(G))
colnames(Combinations) <- paste0("Comb_", 1:ncol(Combinations))

列表 X 包含 ABC:

的唯一值
X
#$A
#[1] 1 2 4

#$B
#[1] 3 2 4

#$C
#[1] 1

然后 expand.grid 构建笛卡尔积 G,即这些唯一值的组合:

G
#  A B C
#1 1 3 1
#2 2 3 1
#3 4 3 1
#4 1 2 1
#5 2 2 1
#6 4 2 1
#7 1 4 1
#8 2 4 1
#9 4 4 1

G <- G[rowSums(G)==7,]后只剩下总和为7的组合:

G
#  A B C
#6 4 2 1
#8 2 4 1

最后将矩阵G中的数据放入data.frame Combinations:

Combinations
#  Comb_1 Comb_2
#A      4      2
#B      2      4
#C      1      1