Skip to content

adjacency list to non-symmetric matrix

4 messages · Sebastian Haunss, arun, William Dunlap +1 more

#
Dear R community,

is there an easy way to convert an adjacency list (or a data-frame) to a non-symmetric matrix?

The adjacency list has the following form:

person group
1 Sam a
2 Sam b
3 Sam c
4 Greg a
5 Tom b
6 Tom c
7 Tom d
8 Mary b
9 Mary d

I need the data in a matrix with persons as rows and groups as columns:

a b c d
Sam 1 1 1 0
Greg 1 0 0 0
Tom 0 1 1 1
Mary 0 1 0 1

I know that there are several possibilities in some of the network packages to convert adjacency lists to symmetric or sparse matrices, but I couldn't find a way to coerce them into affiliation matrices.


kind regards
Sebastian
#
For converting from first dataset to second,

library(reshape2)
#dat1 is data
dcast(dat1,person~group,value.var="group",length)
# ?person a b c d
#1 ? Greg 1 0 0 0
#2 ? Mary 0 1 0 1
#3 ? ?Sam 1 1 1 0
#4 ? ?Tom 0 1 1 1
A.K.


----- Original Message -----
From: Sebastian Haunss <sebastian.haunss at uni-bremen.de>
To: r-help at r-project.org
Cc: 
Sent: Tuesday, February 5, 2013 4:07 AM
Subject: [R] adjacency list to non-symmetric matrix

Dear R community,

is there an easy way to convert an adjacency list (or a data-frame) to a non-symmetric matrix?

The adjacency list has the following form:

person group
1 Sam a
2 Sam b
3 Sam c
4 Greg a
5 Tom b
6 Tom c
7 Tom d
8 Mary b
9 Mary d

I need the data in a matrix with persons as rows and groups as columns:

a b c d
Sam 1 1 1 0
Greg 1 0 0 0
Tom 0 1 1 1
Mary 0 1 0 1

I know that there are several possibilities in some of the network packages to convert adjacency lists to symmetric or sparse matrices, but I couldn't find a way to coerce them into affiliation matrices.


kind regards
Sebastian
#
Try table():
   > adj <- table(d) # 'd' is your data.frame
   > adj
         group
   person a b c d
     Greg 1 0 0 0
     Mary 0 1 0 1
     Sam  1 1 1 0
     Tom  0 1 1 1
If you have duplicate rows in the d then it will
tally them up.  You can can convert positives to
1's with adj[adj>0] <- 1.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
If the order of people in the original data frame is important, one more line matches your example output:
group
person a b c d
  Sam  1 1 1 0
  Greg 1 0 0 0
  Tom  0 1 1 1
  Mary 0 1 0 1

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352