My input is
df1 <- data.frame(Row=c(\"row1\", \"row2\", \"row3\", \"row4\", \"row5\"),
A=c(1,2,3,5.5,5),
B=c(2,2,2
combn
. t
is used to transpose the matrix as you expect it to be formatted.apply
to iterate over the indices created in step 1. Note that we use negative indexing so we don't try to sum the Row column.`
ind <- t(combn(nrow(df1),2))
out <- apply(ind, 1, function(x) sum(df1[x[1], -1] * df1[x[2], -1]))
cbind(ind, out)
out
[1,] 1 2 6.00
[2,] 1 3 7.00
[3,] 1 4 12.65
.....
Yes! This is a matrix multiplication! :-))
First, just to prepare the matrix:
m = as.matrix(df1[,2:4])
row.names(m) = df1$Row
and this is the operation, how easy!
m %*% t(m)
That's it!
One tip - you could define the data.frame this way and it will save you the row.names
command:
df1 <- data.frame(row.names=c("row1", "row2", "row3", "row4", "row5"),A=c(1,2,3,5.5,5), B=c(2,2,2,2,0.5), C= c(1.5,0,0,2.1,3))