如果您不希望结果对象中出现组合名称,那么我们可以结合 @DWin 和 @Owen 的答案的元素,以提供真正的矢量化方法来解决问题。 (您可以将组合名称添加为行名称,并在末尾添加一个额外步骤。)
一、数据:
dat <- read.table(con <- textConnection(" A B C D
w 0 0 1 1
x 0 1 0 1
y 0 0 1 1
z 0 0 0 1
"), header=TRUE)
close(con)
采取combn()
来自 @DWin's Answer 的想法,但将其用于行索引 of dat
:
combs <- combn(seq_len(nrow(dat)), 2)
的行combs
现在索引行dat
我们想要相乘:
> combs
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 1 2 2 3
[2,] 2 3 4 3 4 4
现在我们采用@Owen 展示的想法,即dat[i, ] * dat[j, ]
with i
and j
是第一行和第二行combs
分别。我们将其转换为矩阵data.matrix()
因为这对于大型对象来说会更有效,但是代码将适用于dat
也作为数据框。
mat <- data.matrix(dat)
mat[combs[1,], ] * mat[combs[2,], ]
其产生:
> mat[combs[1,], ] * mat[combs[2,], ]
A B C D
w 0 0 0 1
w 0 0 1 1
w 0 0 0 1
x 0 0 0 1
x 0 0 0 1
y 0 0 0 1
要了解这是如何工作的,请注意mat[combs[k,], ]
生成一个矩阵,其中各行按组合指定的顺序重复:
> mat[combs[1,], ]
A B C D
w 0 0 1 1
w 0 0 1 1
w 0 0 1 1
x 0 1 0 1
x 0 1 0 1
y 0 0 1 1
> mat[combs[2,], ]
A B C D
x 0 1 0 1
y 0 0 1 1
z 0 0 0 1
y 0 0 1 1
z 0 0 0 1
z 0 0 0 1
为了准确获取OP发布的内容,我们可以使用第二个修改行名combn()
call:
> out <- mat[combs[1,], ] * mat[combs[2,], ]
> rownames(out) <- apply(combn(rownames(dat), 2), 2, paste, collapse = "")
> out
A B C D
wx 0 0 0 1
wy 0 0 1 1
wz 0 0 0 1
xy 0 0 0 1
xz 0 0 0 1
yz 0 0 0 1