r - 使用 igraph 根据边缘属性添加多个边缘

标签 r igraph

我想知道是否使用igraph ,可以根据不同边属性的值向图中添加边。

我有一个 data.frame,其中 dput如下:

df <- structure(list(nodeA = c("CFTR", "CFTR", "CFTR", "CFTR", "CFTR", 
"CFTR"), nodeB = c("CYP7A1", "KRT16", "ABCA3", "SLC22A11", 
"PBK", "ACSM1"), score = c(0.239, 0.24, 0.292, 0.269, 
0.233, 0.168), text = c(129L, 0L, 287L, 246L, 
161L, 155L), mining = c(163L, 241L, 413L, 71L, 92L, 56L), 
experiments = c(0L, 0L, 101L, 0L, 75L, 0L), homologs =c(0L, 
0L, 609L, 0L, 0L, 0L)), .Names = c("nodeA", "nodeB", 
"score", "text", "mining","experiments", 
"homologs"), class = "data.frame", row.names = c(NA, 6L))

如果边属性的值不为 0,例如边 g <- graph.data.frame(df, directed=FALSE,我想向图表添加新边 ( CFTR--CYP7A1 ) ,我想添加一对额外的边(一个用于 text ,另一个用于 mining 属性),我对 score 不感兴趣(这是我的图表的权重)

最佳答案

这里有几种方法。

首先,重新排列原始数据似乎更容易一些。将数据设置为长格式并根据列名称分配颜色。

library(reshape2)
# Data in long format 
# Create graph, with edges add when attributes / columns are greater than zero
m <- melt(df, id=1:2)
m <- m[m$value != 0, ] # keep non-zero values
g <- graph.data.frame(m, directed=FALSE)

# Add colours to the edges
cols = c(score="black", text="blue", mining="green", 
                                  experiments="red", homologs="yellow")
plot(g, edge.color=cols[E(g)$variable])
<小时/>

如果您想要原始图形,然后为每个图形添加彩色边缘 属性大于零,可以循环遍历属性 (edge_attr),并在满足条件时添加边 (add_edges)。

我们可以一次添加一条附加边(针对 text 属性显示)

g <- graph.data.frame(df, directed=FALSE)    
names(edge_attr(g)) # attributes

# Which edges should be added conditioned on text attribute being greater than zero
edge_attr(g, "text")
ats <- edge_attr(g, "text") > 0

#Set edges in graph already to black
E(g)$color <- "black"

# Get head and tail of all edges
ed <- get.edgelist(g)

# subset these by the attribute condition
# combine head and tail nodes in correct format for add_edges
# should be c(tail1, head1, tail2, head2, ..., tailn, headn)
ed <- t(ed[ats, 2:1])

# Add the additional edges
g  <- add_edges(g, ed,  color="blue")
plot(g)

或者一次性添加额外的边

g <- graph.data.frame(df, directed=FALSE)    

# Indicator of attribute > 0
ats <- unlist(edge_attr(g)) > 0

# Repeat the head & tail of each edge
# subset so the same length as relevant attributes
ed <- do.call(rbind, replicate(length(edge_attr(g)), get.edgelist(g), simplify=FALSE))
ed <- t(ed[ats, 2:1])
cols <- rep(c("black", "blue", "green", "red", "yellow"), each=length(E(g)))[ats]

g  <- add_edges(g, ed,  color=cols)
plot(g)

关于r - 使用 igraph 根据边缘属性添加多个边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39800516/

相关文章:

检索给定大小 k 的 n 项的所有可能组合,并在另一列上应用函数 sum

r - 如何在R中分配 "cut"范围中点?

python - Python igraph中将有向图转换为无向图

python - 基于顶点名称 Python igraph 执行图的并集

Python-绘图不可用

R:将幂律曲线拟合到数据(c 的起始值)

r - dplyr:汇总每一列并返回列表列

r - 使用lapply时如何命名列表下的列表?

r - 如何将大量 igraph 组合成一个 igraph - R

r - igraph:从顶点 igraph r 开始查找连续连接的顶点