for循环或在多个子图上应用函数

for-loop or apply function on multiple subgraphs

这是 post . You can find reproducible examples of a graph g and a dataframe modules here 的后续问题。从 g,我创建了一个子图 m1,其中包含给定模块中的节点及其边缘数据,例如:

m1 <- as_tbl_graph(g) %>% 
  activate(nodes) %>% 
  filter(module == 1)

m1
# A tbl_graph: 37 nodes and 93 edges
#
# An undirected simple graph with 1 component
#
# Node Data: 37 x 2 (active)
  name                             module
  <chr>                             <int>
1 Antigua and Barbuda                   1
2 Aruba                                 1
3 Australia                             1
4 Barbados                              1
5 Belize                                1
6 Bolivia (Plurinational State of)      1
# ... with 31 more rows
#
# Edge Data: 93 x 2
   from    to
  <int> <int>
1     1     7
2     4     7
3     6     8
# ... with 90 more rows
> 

我想编写一个 for 循环或应用函数来为所有模块计算以下计算。

m1 <- as_tbl_graph(g) %>% 
  activate(nodes) %>% 
  filter(module == 1)

nodedeg <- as.data.frame(degree(m1))
meandeg <- mean(nodedeg$`degree(m1)`)
sd <- sd(nodedeg$`degree(m1)`)

z <- (nodedeg-meandeg)/sd

我的预期输出是一个数据框,每个国家/地区都有一个 z 值。

您可以像下面那样尝试 induced_subgraph group_by

g %>%
    as_tbl_graph() %>%
    activate(nodes) %>%
    as.data.frame() %>%
    group_by(module) %>%
    mutate(z = scale(induced_subgraph(g, name) %>% degree())) %>%
    ungroup()