0

使用 furrr 对 tidygraph 中心性函数进行并行计算会引发错误:

“mutate_impl(.data, dots) 中的错误:评估错误:不应直接调用此函数。”

这是我的代码:

library(tidyverse)
library(tidygraph)
library(furrr)

H <- play_islands(5, 10, 0.8, 3)

cent <- tribble(
  ~f,      ~params,                  
  "centrality_degree", list(H),  
  "centrality_authority", list(H)  
)

cent %>% 
  mutate(centrality = future_invoke_map(f, params, .options = future_options(packages = c("tidygraph", "tidyverse"))))

我应该如何解决这个问题?

4

1 回答 1

1

我相信您对 tidygraph 的工作方式有误解,这会阻止您正确编码。

函数centrality_degree()centrality_authority()都在mutate()语句中使用(请参阅https://tidygraph.data-imaginist.com/reference/centrality.html)。

library(tidygraph)
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#> 
#>     filter
create_notable('bull') %>%
  activate(nodes) %>%
  mutate(importance = centrality_authority())
#> # A tbl_graph: 5 nodes and 5 edges
#> #
#> # An undirected simple graph with 1 component
#> #
#> # Node Data: 5 x 1 (active)
#>   importance
#>        <dbl>
#> 1      0.869
#> 2      1    
#> 3      1    
#> 4      0.434
#> 5      0.434
#> #
#> # Edge Data: 5 x 2
#>    from    to
#>   <int> <int>
#> 1     1     2
#> 2     1     3
#> 3     2     3
#> # ... with 2 more rows

reprex 包(v0.3.0)于 2020-07-03 创建

注意语句中centrality_authority()的函数。mutate()换句话说,您需要将这些函数包装在另一个函数周围以传递给这些furrr函数。

另外,请注意正确使用这些函数的结果返回一个tidygraph对象。有一个函数graph_join()可以让我们将多个图连接在一起。因此,与您提出的计划类似的计划是计算单独的中心性度量,每个都返回一个图形对象,然后将它们与graph_join().

有了这些知识,我们可以将其编码如下(注意对您的代码进行的小改动,我们必须向节点添加一些唯一的 ID 名称,以便我们可以将图形连接在一起)。

# Load libraries
library(tidyverse)
library(tidygraph)
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#> 
#>     filter
library(furrr)
#> Loading required package: future
 
# Create example graph
H <- play_islands(5, 10, 0.8, 3) %>%
  mutate(name = 1:50)  # Add node names to join
  
# Create functions to add centrality measures
f_c_deg <- function(x) x %>% mutate(c_deg = centrality_degree())
f_c_aut <- function(x) x %>% mutate(c_aut = centrality_authority())
  
# Setup mapping data frame
cent <- tribble(
  ~f,      ~params,                  
  "f_c_deg", list(x = H),
  "f_c_aut", list(x = H)
)
  
# Apply functions and join
res <- future_invoke_map(cent$f, cent$params)
one_g <- Reduce(graph_join, res)  # Put together results and view single graph
#> Joining, by = "name"

one_g
#> # A tbl_graph: 50 nodes and 416 edges
#> #
#> # A directed acyclic multigraph with 1 component
#> #
#> # Node Data: 50 x 3 (active)
#>    name c_deg c_aut
#>   <int> <dbl> <dbl>
#> 1     1     7 0.523
#> 2     2     9 0.661
#> 3     3     9 0.670
#> 4     4     8 0.601
#> 5     5     9 0.637
#> 6     6    11 0.823
#> # ... with 44 more rows
#> #
#> # Edge Data: 416 x 2
#>    from    to
#>   <int> <int>
#> 1     1     2
#> 2     1     3
#> 3     1     4
#> # ... with 413 more rows

reprex 包(v0.3.0)于 2020-07-03 创建

于 2020-07-03T14:44:53.277 回答