Search code examples
rnetwork-programmingadjacency-matrix

Create an adjacency matrix from binary survey responses in R


I have a data frame representing different people's policy preferences, where rows represent individuals.

Here is a toy example, using hypothetical data from "Frank," "Sarah," "Josh," and "Elyse". In this example, participants have indicated their endorsement on three political policies (tax cuts, universal health care, extended term limits), such that "1" represents endorsement and "0" represents opposition to the policy.

    d<-data.frame("Name"=c("Frank","Sarah","Josh","Elyse"),
    "tax_cuts"=c(0,1,1,1),
    "u_healthcare"=c(1,1,0,0),
    "ex_term"=c(0,0,1,0))
d

  Name    tax_cuts  u_healthcare ex_term
 Frank        0            1       0
 Sarah        1            1       0
  Josh        1            0       1
 Elyse        1            0       0

How can I create a matrix where edges indicate the number of co-endorsements a policy. For example, Sarah co-endorsed tax cuts and extended term limits whereas Josh co-endorsed extended term limits and tax cuts, so there would be 1 co-endorsement for these policies. The resulting matrix would be a 3-3 square matrix with the following values.

    mat<-rbind(c(0, 1, 1),c(1,0,0), c(1,0,0))
    rownames(mat)<-c("tax_cuts","u_healthcare","ex_term")
    colnames(mat)<-c("tax_cuts","u_healthcare","ex_term")
    print(mat)

                tax_cuts  u_healthcare ex_term
tax_cuts            0            1        1
u_healthcare        1            0        0
ex_term             1            0        0

Solution

  • We can do this with matrix multiplication:

    t(d[-1]) %*% as.matrix(d[-1])
                 tax_cuts u_healthcare ex_term
    tax_cuts            3            1       1
    u_healthcare        1            2       0
    ex_term             1            0       1
    

    The diagonal is the count of each individual endorsement. You can set it to 0 if you prefer...

    coendorse = t(d[-1]) %*% as.matrix(d[-1])
    diag(coendorse) = 0
    coendorse
    #              tax_cuts u_healthcare ex_term
    # tax_cuts            0            1       1
    # u_healthcare        1            0       0
    # ex_term             1            0       0