rnetwork-programmingigraphnavertex

R: Change vertex attribute of a particular vertex


I have a network that looks like the following:

> get.vertex.attribute(g)
$name
[1] "T1" "A1"  "A2"  "A3"  "A3" 

$color
[1] NA        "#D53E4F" "#D53E4F" "#F6E68E" "#EE6445"

$weight
[1] NA 34 15 11  6

I am hoping to replace the NA value in V(g)$color with black, and the V(g)$weight with a number. Would anyone know how to set the vertex value for a particular vertex, especially one that has an NA vertex attribute?


Solution

  • You can use set.vertex.attribute

    get.vertex.attribute(g)
    #> $name
    #> [1] "T1" "A1" "A2" "A3" "A3"
    #> 
    #> $color
    #> [1] NA        "#D53E4F" "#D53E4F" "#F6E68E" "#EE6445"
    #> 
    #> $weight
    #> [1] NA 34 15 11  6
    
    g <- set.vertex.attribute(g, "color", 1, "black")
    g <- set.vertex.attribute(g, "weight", 1, 100)
    
    get.vertex.attribute(g)
    #> $name
    #> [1] "T1" "A1" "A2" "A3" "A3"
    #> 
    #> $color
    #> [1] "black"   "#D53E4F" "#D53E4F" "#F6E68E" "#EE6445"
    #> 
    #> $weight
    #> [1] 100  34  15  11   6
    

    Created on 2022-04-26 by the reprex package (v2.0.1)


    Data

    library(igraph)
    
    g <- make_graph(~T1-A1-A2-A3-A4)
    g <- set.vertex.attribute(g, "name", 1:5,  c("T1", "A1", "A2", "A3", "A3"))
    g <- set.vertex.attribute(g, "color", 1:5,
                              c( NA, "#D53E4F", "#D53E4F", "#F6E68E", "#EE6445"))
    g <- set.vertex.attribute(g, "weight", 1:5, c(NA, 34, 15, 11,  6))