在igraph中从数据帧列表中生成多个图形对象

时间:2017-01-18 17:21:50

标签: r dataframe igraph mapply

我有两个大约80个数据帧的列表 - 一个用于节点,另一个用于边缘。我想使用igraph函数graph_from_dataframe来连接节点和边缘数据框组成一个igraph对象列表。目前我一直在尝试这个:

glst <- mapply(graph_from_data_frame, 
           d=ListOfEdgeDfs, 
           vertices=ListOfNodeDfs,
            SIMPLIFY = FALSE,
           directed =F)

但是,这会显示错误消息:

Error in (function (d, directed = TRUE, vertices = NULL)  : 
  Some vertex names in edge list are not listed in vertex data frame

有没有人对如何做到这一点有任何想法?

1 个答案:

答案 0 :(得分:2)

以下工作(对于2个图表的列表,同样适用于任意数量的图表,可以确保数据框架结构相似):

ListOfEdgeDfs <- list(data.frame(from=letters[1:3], to=c('b', 'c', 'd')), 
                      data.frame(from=rep('a',3), to=c('b', 'c', 'd')))
ListOfEdgeDfs
#[[1]]
#  from to
#1    a  b
#2    b  c
#3    c  d
#[[2]]
#  from to
#1    a  b
#2    a  c
#3    a  d

ListOfNodeDfs <- list(data.frame(node=letters[1:4]), data.frame(node=letters[1:4]))
ListOfNodeDfs
#[[1]]
#  node
#1    a
#2    b
#3    c
#4    d
#[[2]]
#  node
#1    a
#2    b
#3    c
#4    d

library(igraph)
glst <- mapply(graph_from_data_frame, 
               d=ListOfEdgeDfs, 
               vertices=ListOfNodeDfs,
               SIMPLIFY = FALSE,
               directed =F)
par(mfrow=c(1,2))
#plot(glst[[1]])
#plot(glst[[2]])

<强> [EDITED]

试试这个:

n <- 2 # number of graphs
par(mfrow=c(2,1)) # if you have 100 graphs, try par(mfrow=c(10,10)) e.g.
invisible(sapply(1:n, function(i) plot(glst[[i]], vertex.size=50)))

enter image description here