Skip to content

Rense Corten

Computational sociology, social networks, and cooperation

Menu
  • About me
  • Blog
  • Research
    • Social Network Analysis with Stata
  • Teaching
Menu

From adjacancy matrix to edgelist in Stata

Posted on 19/07/2012

Every once in a while, people e-mail me with questions about netplot, and probably the most frequently asked question is how to convert data from an adjacency matrix into an edgelist, which is the data format that netplot expects.  I finally took the time to write some decent code to do it, and I might as well share it here. In principle it’s quite simple. If you want your data as a simple edgelist (or arclist, strictly speaking), a reshape command is almost all that you need. However, isolated nodes will not show up in the resulting edgelist. If you want to create an “extended edgelist” that includes also isolates nodes (for example because you want them to be drawn by netplot), things become slightly more complicated. In the code below, section #3 is dedicated to solving that problem; I you don’t want or need it, you can just skip that part. My feeling is that section #3 could be further simplified; suggestions are welcome!


// #1 Example dataset; random adjacency matrix with N=4; node 4 is isolated

clear
set seed 223344
set obs 4

forval x = 1(1)4{
gen v`x' =(uniform()>.5)
replace v`x'=0 if _n==`x'
replace v`x' = 0 if _n == 4
}
replace v4 = 0
gen n1 = _n

list

// #2 Transform into edgelist

reshape long v, i(n1) j(n2)

// #3 This section only to keep isolates in the data. Skip if you want a
//    regular edgelist without isolates.

gen id_arc = _n
bys n1: egen degree1 = total(v)
bys n2: egen degree2 = total(v)

sort n1

reshape long n degree, i(id_arc) j(nseq)

bys n: egen totaldegree = total(degree)

gen isolated = totaldegree == 0
drop totaldegree

reshape wide n degree isolated, i(id_arc) j(nseq)

replace n2 = . if isolated1 == 1

bys n1: gen tag = _n==1
drop if isolated1 & tag==0
drop isolated*
keep n1 n2 v

// #4

keep if v==1 | n2==.
drop v

list // Tada!

netplot n1 n2,label arrows // draw the network!

Recent Comments

  • michal on Duncan Watts on common sense
  • Rense on On unsolved sociological questions
  • Gabriel rossman on On unsolved sociological questions

Categories

  • Everything (8)
  • In het Nederlands (1)
  • Other (2)
  • Politics (2)
  • Science (4)
  • SNA with stata (9)
  • Social Networks (27)
  • Social Science (16)
  • Sociology (32)
  • Stata (7)
  • The Netherlands (8)
  • The Universe (2)

Blogroll

  • Brokering the Closure
  • Chris Snijders
  • Code and Culture
  • Orgtheory.net
  • Permutations
  • Social Science Statistics Blog

Links

  • GECS
  • ICS
  • INSNA
  • International Network of Analytical Sociologists
  • Mathematical Sociology Section (ASA)
  • My Google Scholar profile
  • My official UU webpage

Contact

r.corten [at] uu.nl
@RenseC

Subscribe

RSS Feed RSS
©2026 Rense Corten | Design: Newspaperly WordPress Theme