1

I have a graph, with an attribute W. I want to mutate the average W of the neighbors. I want to keep the code as simple as possible, trying to avoid maps and other explicit functions for vectorisation, because this is for didactic purposes.

My code, trying to show well each passage would look like this:

set.seed(1810)

create_ring(40) %>%
  mutate(id = row_number()) -> ring

ring %>%
      mutate(W = rnorm(40,75,15)) %>%
      mutate(Neighs = local_members(order = 1,
                                    mindist = 1),
             k = local_size(order = 1,
                            mindist = 1)) -> ring
    
ring %>%
  mutate(
    W_neighs = map_dbl(
      Neighs,
      function(x) mean(W[id %in% unlist(x)])
    )
  )

Is there a way to perform these operations without recurring to map? Tidygraph has a similar wrapper that is local_ave_degree, that wraps igraph::knn, that wraps something in C...

Also, I would be interested in an explanation if morph can be useful for these operations.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
GiulioGCantone
  • 195
  • 1
  • 10

1 Answers1

0

I guess you can use ego from igraph to save a lot of lines (no need to create the columns Neighs or k), e.g.,

set.seed(1810)

ring <- create_ring(40) %>%
  mutate(id = row_number()) %>%
  mutate(W = rnorm(40, 75, 15)) %>%
  mutate(W_neighs = 
    as.igraph(.) %>%
      ego(order = 1, mindist = 1) %>%
      sapply(function(v) mean(v$W))
  )

and you will see

> ring
# A tbl_graph: 40 nodes and 40 edges
#
# An undirected simple graph with 1 component
#
# Node Data: 40 × 3 (active)
     id     W W_neighs
  <int> <dbl>    <dbl>
1     1  84.3     96.1
2     2  84.5     91.9
3     3  99.4     91.2
4     4  97.9     67.9
5     5  36.4     89.4
6     6  80.8     51.2
# … with 34 more rows
#
# Edge Data: 40 × 2
   from    to
  <int> <int>
1     1     2
2     2     3
3     3     4
# … with 37 more rows
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • I am not sure that I want to use a function from igraph in a lecture on tidygraph. I want those columns because students have to understand what's happening. Students have always a poor understanding of maps and applies. This is why I wanted to avoid them. – GiulioGCantone Sep 13 '22 at 18:34
  • @GiulioGCantone If you don't want `igraph`, I suggest you remove the `igraph` tag under your post to avoid confusion. BTW, what is your ultimate goal? If you want to avoid `map` or `*apply`, you could use `for` loop instead, but it seems you are after something else .... – ThomasIsCoding Sep 13 '22 at 20:06