network-programmingstataadjacency-matrixadjacency-listpeer

Create adjacency matrix from a list of Id and the corresponding club they are part of


The structure of the data in Stata looks something like this:

id    club_id
1       1
2       1 
3       2
4       2
5       2
6       3
7       3
8       3
9       3

I assume that the network corresponds to the club; hence the adjacency matrix (ordering the data by club) should be block diagonal. I have about 7000 observations. I am new to Mata. I tried to write many variations of the following code but it won't work:

sort id club_id

bys club_id: gen dim = _n     //get the position of the component of the network

mkmat id, mat(id)
mkmat club_id, mat(club_id)
mkmat dim, mat(dim)


local nsubj = _N 

mata:

group_id = st_matrix("id")
AID = st_matrix("club_id")
dim = st_matrix("dim")

adj = J(`nsubj',`nsubj',0)


for (i=1; i<=20; i++) {                   //iteration over each column
    if (club_id[i] == club_id[i+1]) {
        for (k=0, k<= dim[i]-1, k++) {   // the number of columns to be filled
            adj[i, i+k] = 1              // fill the upper part of the matrix
        }
    }

}

end

And I thought to reverse the order of dim to fill the lower part of the matrix. I tried many variations of the code and I don't understand what is wrong.


Solution

  • Here is an approach to create an adjacency matrix without Mata. Maybe that can get you started.

    *Replicate data example
    clear
    set obs 9
    gen id = _n 
    expand 9
    bysort id: gen club_id = _n
    
    *Generate a variable with a value
    gen wins = round(runiform()*10)
    
    *Rename the future variable name
    gen club = "club"
    egen club_id2 = concat(club club_id )
    drop club club_id
    
    *Reshape data
    reshape wide wins, i(id) j(club_id2) string