R 潮汐仪中的过滤器
考虑这个简单的例子R 潮汐仪中的过滤器,r,igraph,tidygraph,R,Igraph,Tidygraph,考虑这个简单的例子 library(tidygraph) mynodes <- tibble(id = c(1,2,3,4,5)) myedges <- tibble(from = c(1,1,1,5), to = c(1,2,3,4), power = c(10,10,10,3)) tbl_graph(nodes = mynodes, edges = myedges) # A tbl_graph: 5 n
library(tidygraph)
mynodes <- tibble(id = c(1,2,3,4,5))
myedges <- tibble(from = c(1,1,1,5),
to = c(1,2,3,4),
power = c(10,10,10,3))
tbl_graph(nodes = mynodes, edges = myedges)
# A tbl_graph: 5 nodes and 4 edges
#
# A directed multigraph with 2 components
#
# Node Data: 5 x 1 (active)
id
<dbl>
1 1
2 2
3 3
4 4
5 5
#
# Edge Data: 4 x 3
from to power
<int> <int> <dbl>
1 1 1 10
2 1 2 10
3 1 3 10
# ? with 1 more row
一种可能的解决方案是将数据转换为
子图
,并按id
对其进行过滤:
通过id
创建子图
和过滤器
:
或者您可以通过id
进行过滤,但这不是最简单的方法,因为您首先必须识别id
,它包含在power
3中:
mygraph %>% filter(id %in% c(5, 4))
# A tbl_graph: 2 nodes and 1 edges
#
# A rooted tree
#
# Node Data: 2 x 1 (active)
id
<dbl>
1 4
2 5
#
# Edge Data: 1 x 3
from to power
<int> <int> <dbl>
1 2 1 3
注
请注意,转换为
data.frame
将更改id
变量名,因此您可以使用rename
再次更改它。实际上,有一个非常简单的解决方案
activate(nodes) %>%
filter(!node_is_isolated())
您可以使用.E()&.N()FCN访问节点或边,而另一个在tidygraph中激活
这里的引言中提到了这一点:
因此,要根据边属性筛选节点,可以在激活节点时使用.E()函数:
mygraph %>%
activate("nodes") %>%
filter(.E()$power[id] == 3)
很有趣,谢谢!但是使用
作为\u data\u frame
会删除额外的节点变量…因此,它应该是:mygraph%%>%activate(edges)%%>%filter(power==3)%%>%activate(nodes)%%>%filter(!node\u is_insolated())
@NOOBIE,谢谢。我能用上面的代码画出非孤立节点的近邻吗?真奇怪!感谢您的评论,tidygraph对顺序非常严格……首先,过滤边,然后激活节点和过滤器(!node_is_isolated())……没有反向工作
mygraph %>% filter(id %in% c(5, 4))
# A tbl_graph: 2 nodes and 1 edges
#
# A rooted tree
#
# Node Data: 2 x 1 (active)
id
<dbl>
1 4
2 5
#
# Edge Data: 1 x 3
from to power
<int> <int> <dbl>
1 2 1 3
library(ggraph)
mygraph %>% igraph::as_data_frame() %>%
filter(power == 3) %>%
as_tbl_graph () %>%
rename(id = name) %>%
ggraph() +
geom_edge_fan() +
geom_node_point(aes(color = id)) +
theme_graph()
activate(nodes) %>%
filter(!node_is_isolated())
mygraph %>%
activate("nodes") %>%
filter(.E()$power[id] == 3)