我在麻烦某些idy中相对简单的Tidygraph操作时遇到麻烦。
我特别想分析不同顺序的特定社区。我认为我需要为此使用Morphs,但我只是没有使它起作用。
library(tidygraph)
library(ggraph)
net <- tibble::tibble(A = letters[1:6],
B = rep(c("x", "y"), each = 3)) %>%
tidygraph::as_tbl_graph()
我想分析关于x的邻域。
net %>%
ggraph(layout = "nicely") +
geom_edge_link() +
geom_node_point(size = 10, fill = "white", shape = 21) +
geom_node_text(aes(label = name)) +
theme_graph()
提取节点x的邻域。
v <- net %>%
tidygraph::as.igraph() %>%
igraph::neighborhood(nodes = "x", order = 1)
igraph::induced_subgraph(net, vids = unlist(v)) %>%
tidygraph::as_tbl_graph() %>%
ggraph(layout = "nicely") +
geom_edge_link() +
geom_node_point(size = 10, fill = "white", shape = 21) +
geom_node_text(aes(label = name)) +
theme_graph()
以下实现返回相同的错误:
net %>%
tidygraph::morph(to_local_neighborhood, node = "x", order = 1, mode = "all")
net %>%
to_local_neighborhood(node = "x", order = 1, mode = "all")
Error in if (is.numeric(v) && any(v < 0)) { : missing value where TRUE/FALSE needed
答案 0 :(得分:1)
如果您不太熟悉tidygraph API,则使用一些基本的R函数比使用GitHub-linked solution多一些回旋,但是我们可以使用@camille's insight获得节点的索引,以要求使用node
参数为数字。
library(tidygraph)
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#>
#> filter
library(ggraph)
#> Loading required package: ggplot2
# Example
net <- tibble::tibble(A = letters[1:6],
B = rep(c("x", "y"), each = 3)) %>%
tidygraph::as_tbl_graph()
# Get row name index as integer because tidygraph requirement
node_tbl <- data.frame(activate(net, nodes)) # Make sure focus on nodes
node_idx <- rownames(node_tbl)[node_tbl$name == "x"]
node_idx <- as.integer(node_idx) # tidygraph needs it as number, not string
net %>%
tidygraph::convert(to_local_neighborhood,
node = node_idx,
order = 1,
mode = "all") %>%
ggraph(layout = "nicely") +
geom_edge_link() +
geom_node_point(size = 10, fill = "white", shape = 21) +
geom_node_text(aes(label = name)) +
theme_graph()
由reprex package(v0.3.0)于2020-07-03创建
这是GitHub链接的解决方案,通过在转换中使用.N()
来引用which(.N()$name == "x")
中的节点表,从而更多地利用了tidygraph的API。
library(tidygraph)
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#>
#> filter
library(ggraph)
#> Loading required package: ggplot2
# Example
net <- tibble::tibble(A = letters[1:6],
B = rep(c("x", "y"), each = 3)) %>%
tidygraph::as_tbl_graph()
net %>%
tidygraph::convert(to_local_neighborhood,
node = which(.N()$name == "x"),
order = 1,
mode = "all") %>%
ggraph(layout = "nicely") +
geom_edge_link() +
geom_node_point(size = 10, fill = "white", shape = 21) +
geom_node_text(aes(label = name)) +
theme_graph()
由reprex package(v0.3.0)于2020-07-03创建