使用furrr对tidygraph中心度函数的并行计算会引发错误:
“ mutate_impl(.data,点)中的错误:评估错误:这 函数不应直接调用。”
这是我的代码:
library(tidyverse); library(tidygraph)
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"))))
我该如何解决?
答案 0 :(得分: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 package(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 package(v0.3.0)于2020-07-03创建