0

I am very new to R.

I am trying to code the following using tidygraph:

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

where g is my graph, activated is the attribute I want to add, seeds is a predefined vector. I am successful in doing the first part using tidygraph:

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

I was wondering how to do the second part.

user438383
  • 5,716
  • 8
  • 28
  • 43
AC24
  • 5
  • 2
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 05 '21 at 05:06

1 Answers1

0

I am not sure what your seeds variable looks like. This solution assumes seeds is a numeric vector corresponding to node names. Here is the code to reproduce your graph.

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

Here is the solution. row_number() was used because node names correspond to row numbers in this random graph example. If you have a variable for node names, you can simply replace row_number(). On a separate note, tidygraph sets active the dataframe for nodes by default. So, no need to activate nodes.

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
Zaw
  • 1,434
  • 7
  • 15