1

This is a follow-up question to this post Calculation based on list elements. You can find reproducible examples of a graph g and a dataframe modules here Node links across modules with graph and dataframe. From g, I have created a subgraph m1, which contains nodes in a given module and their edge data, like:

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
> 

I would like to write a for loop or apply function that computes the following calculation for all modules.

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

My expected output is a dataframe with a z value for each country.

camille
  • 16,432
  • 18
  • 38
  • 60
MoonS
  • 117
  • 7
  • @ThomasIsCoding Sorry, see edit in my updated post. – MoonS Jun 24 '21 at 13:38
  • The modules data frame is supposed to be joined to the graph data? It'd be easier to follow if all the data needed for this were in one place (and ideally one object already merged together) – camille Jun 24 '21 at 14:15

1 Answers1

1

You can try induced_subgraph like below with group_by

g %>%
    as_tbl_graph() %>%
    activate(nodes) %>%
    as.data.frame() %>%
    group_by(module) %>%
    mutate(z = scale(induced_subgraph(g, name) %>% degree())) %>%
    ungroup()
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thanks, this is helpful, although I'd also like to calculate (degs - the mean degree of the node's module)/the standard deviation of the node's module. As specified by z in my post. – MoonS Jun 24 '21 at 14:04
  • @MoonS See my updated solution. You can use `scale` to normalize the degrees. No need `mean` or `sd` – ThomasIsCoding Jun 24 '21 at 14:07