简体   繁体   中英

Convert Adjacency Matrix into Edgelist (csv file) for Cytoscape

I have a large (200 columns/rows) adjacency matrix in a csv file. This details interactions between individuals. I would like to convert this file into an edgelist, it can be done manually, but would take an enormous amount of time.

A small subset of the data is shown below (the first cell is a space):

        A   B   C   
    A   0   0   1   
    B   0   0   1   
    C   1   0   0   

I would like to transform this into this:

    A  1  C
    B  1  C
    C  1  A

This is just example data. Essentially what I want is to plot the how these nodes interact, and from it plot a network of these interactions. I have tried the following code in the R package PCIT but it returns an error:

    install.packages("PCIT")
    library(PCIT)
    input=read.csv('mouse.csv',header=TRUE,row.names=1,check.names=FALSE)
    setwd('/Users/Plosslab/Documents/PythonStuff')
    getEdgeList(input, rm.zero=TRUE)

But I get the following error:

    Error in structure(.Internal(as.vector(x, "double")), Csingle = TRUE) : 
    (list) object cannot be coerced to type 'double'

Get data:

m <- as.matrix(read.table(text="
     A   B   C   D
    A   0   0   0   1
    B   0   0   1   0
    C   1   0   0   1",
   header=TRUE))

How about

w <- which(m==1,arr.ind=TRUE)
data.frame(r=rownames(m)[w[,"row"]],
           i=1,
           c=colnames(m)[w[,"col"]])
##   r i c
## 1 C 1 A
## 2 B 1 C
## 3 A 1 D
## 4 C 1 D

(Do you care about the order ... ?)

PCIT assumes symmetry anyway, so that might be a problem for you.

with open('input.csv') as infile:
    infile.readline()
    for row in csv.reader(infile, delimiter='\t'):
        src = row[0]
        weights = [int(i) for i in row[1:]]
        for dest, weight in zip("ABC", weights):
            if not weight: continue
            print(src, weight, dest)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM