首页 > 解决方案 > 有没有办法使用 tidygraph 激活节点子集?

问题描述

我很陌生R

我正在尝试使用 tidygraph 编写以下代码:

V(g)$activated <- F
V(g)[seeds]$activated=T

g我的图表在哪里,activated是我要添加的属性,seeds是预定义的向量。我成功地使用了第一部分tidygraph

g%<>%activate(nodes)%>%
  mutate(activated=F)

我想知道如何做第二部分。

标签: rtidygraph

解决方案


我不确定你的seeds变量是什么样的。此解决方案假定seeds是一个与节点名称相对应的数字向量。这是重现图表的代码。

library(igraph)
library(tidygraph)
library(tidyverse)

g <- play_erdos_renyi(10, .2)
seeds <- 1:3
V(g)$activated <- FALSE
V(g)[seeds]$activated <- TRUE
g

# # A tbl_graph: 10 nodes and 16 edges
# #
# # A directed simple graph with 1 component
# #
# # Node Data: 10 x 1 (active)
# activated
# <lgl>    
# 1 TRUE     
# 2 TRUE     
# 3 TRUE     
# 4 FALSE    
# 5 FALSE    
# 6 FALSE    
# # ... with 4 more rows
# #
# # Edge Data: 16 x 2
# from    to
# <int> <int>
# 1     8     1
# 2     4     2
# 3     1     3
# # ... with 13 more rows

这是解决方案。row_number()之所以使用,是因为节点名称对应于此随机图示例中的行号。如果您有节点名称的变量,您可以简单地替换row_number(). 在单独的注释中,tidygraph默认情况下将节点的数据框设置为活动状态。因此,无需激活节点。

g <- play_erdos_renyi(10, .2)
g |> 
  mutate(activated = row_number() %in% seeds)
  
# # A tbl_graph: 10 nodes and 16 edges
# #
# # A directed simple graph with 1 component
# #
# # Node Data: 10 x 1 (active)
# activated
# <lgl>    
# 1 TRUE     
# 2 TRUE     
# 3 TRUE     
# 4 FALSE    
# 5 FALSE    
# 6 FALSE    
# # ... with 4 more rows
# #
# # Edge Data: 16 x 2
# from    to
# <int> <int>
# 1     8     1
# 2     4     2
# 3     1     3
# # ... with 13 more rows

推荐阅读