The answer above by @A5C1D2H2I1M1N2O1R2T1 is not entirely correct due to index order in the upper.tri
assignment.
The answer by @Valentin_Stefan is, using the outer product.
You will only see this when using four elements.
df <- data.frame(list(
"Group" = c("A", "B", "C", "D"),
"v.1" = c( 1, 1, 1, 3 ),
"v.2" = c( 1, 1, 1, 2 )
))
m <- matrix(0, nrow = nrow(df), ncol = nrow(df),
dimnames=list(df$Group, df$Group))
m[lower.tri(m)] <- combn(df$v.1, 2, FUN=diff)
m[upper.tri(m)] <- combn(df$v.2, 2, FUN=diff)
m
# A B C D
# A 0 0 0 0
# B 0 0 1 1
# C 0 0 0 1
# D 2 2 2 0
(see the m[2,3]
element which should be at m[1,4]
instead)
I would transpose to correct; maybe there is an easier way?
n <- matrix(0, nrow = nrow(df), ncol = nrow(df),
dimnames=list(df$Group, df$Group))
n[lower.tri(n)] <- combn(df$v.2, 2, FUN=diff)
n <- t(n)
n[lower.tri(n)] <- combn(df$v.1, 2, FUN=diff)