Input file:
df1 <- data.frame(row.names=c(\"w\",\"x\",\"y\",\"z\"),
A=c(0,0,0,0),
B=c(0,1,0,0),
C=c(1,
dat <- read.table(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)
> combos <- combn(rn,2)
> combos
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "w" "w" "w" "x" "x" "y"
[2,] "x" "y" "z" "y" "z" "z"
apply(combos,2, function(x) c(x[1], x[2], unlist(dat[x[1],]*dat[x[2],])))
[,1] [,2] [,3] [,4] [,5] [,6]
"w" "w" "w" "x" "x" "y"
"x" "y" "z" "y" "z" "z"
A "0" "0" "0" "0" "0" "0"
B "0" "0" "0" "0" "0" "0"
C "0" "1" "0" "0" "0" "0"
D "1" "1" "1" "1" "1" "1"
So the final solution:
t( apply(combos,2, function(x) c(x[1], x[2], unlist(dat[x[1],]*dat[x[2],]))) )
If you convert the combos to a dataframe you would also be able to cbindmatrix as type "numeric":
cbind( as.data.frame(t(combos)),
t( apply(combos,2, function(x)
unlist(dat[x[1],]*dat[x[2],]))) )
V1 V2 A B C D
1 w x 0 0 0 1
2 w y 0 0 1 1
3 w z 0 0 0 1
4 x y 0 0 0 1
5 x z 0 0 0 1
6 y z 0 0 0 1