dat <- data.frame(
names <- unique(c(dat$source, dat$target))
dat$source <- factor(dat$source, levels = names) dat$target <- factor(dat$target, levels = names)
mat <- xtabs(count ~ source + target, data = dat) mat[lower.tri(mat)] <- t(mat)[lower.tri(mat)] mat target source A B C D A 0 4 5 6 B 4 0 3 3 C 5 3 0 5 D 6 3 5 0