Search code examples
rchord-diagram

Adjacency Matrix from source target dataset


I have a dataset as follows

Var1   Var2   Count
A       B      3
A       C      4
A       D      10
A       L      6

I need to create an adjacency matrix for usage downstream in creating a chord diagram. I am looking for an efficient way to get it.

    A   B   C  D  L
A   0   3   4  10 6
B   3   0   0  0  0
C   4   0   0  0  0
D   10  0   0  0  0
L   6   0   0  0  0

I am looking for a visualization as follows

Chord Diagram


Solution

  • Assuming you're talking about just the symmetric matrix generation:

    dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text='
    Var1   Var2   Count
    A       B      3
    A       C      4
    A       D      10
    A       L      6')
    
    vars <- sort(unique(unlist(dat[c("Var1","Var2")])))
    m <- matrix(0, nr=length(vars), nc=length(vars), dimnames=list(vars,vars))
    m[as.matrix(dat[c("Var1","Var2")])] <- m[as.matrix(dat[c("Var2","Var1")])] <- dat$Count
    m
    #    A B C  D L
    # A  0 3 4 10 6
    # B  3 0 0  0 0
    # C  4 0 0  0 0
    # D 10 0 0  0 0
    # L  6 0 0  0 0