假设我有一个基于以下边缘的网络图“ G”:
edges <- data.frame(
from=c(1,1,4,4,4,5,5,6),
to= c(2,3,5,6,7,6,7,7))
G <- graph_from_data_frame(d=edges, directed=F)
此示例显然包含2个子网,第一个具有节点1,2,3,第二个具有节点4,5,6,7。我想:
因此,在此示例中,该函数将理想地创建一个对象,该对象的行数与G中的节点数一样多,并且分为两列:第一列包含一个指示子网ID的向量,第二列包含一个大小(gsize )。 。
result <- data.frame(
ID=c(1,1,2,2,2,2,2,2),
gsize=c(3,3,3,4,4,4,4,4))
G <- graph_from_data_frame(d=edges, directed=F)
我是使用igraph的新手,所以也许有一个功能可以做到这一点。非常感谢!
library(igraph)
library(dplyr)
edges <- data.frame(
from=c(1,1,4,4,4,5,5,6),
to= c(2,3,5,6,7,6,7,7))
G <- igraph::graph_from_data_frame(d=edges, directed=F)
# find subnetworks using louvain algorithm and adding to community in graph
louvain_partition <- igraph::cluster_louvain(G)
G$community <- louvain_partition$membership
# create requested dataframe
df <- data.frame(node_ID = as.vector(V(G)), community = G$community)
required_df <- df %>%
dplyr::inner_join(df %>%
dplyr::group_by(community) %>%
dplyr::count(name = "community_size")
)