Assigning graph attributes using a function in R using switch()

138 Views Asked by At

I have a follow up question to the one I asked here.

I want to build a function that will assign attributes to a graph based on a certain parameter (called lev in the example below). Here is my toy graph:

toy.graph <- graph.formula(121-221,121-345,121-587,345-587,221-587,490,588)

and here is a sample function:

deco2 <- function(x, lev){
      switch(lev,
            one = {V(x)$color <- "red"},
            two = {V(x)$color <- "yellow"})
      return(x)
}

It seems that the color attribute is being added to my graph:

toy.graph <- deco2(toy.graph, lev="one")
> toy.graph
IGRAPH UN-- 6 5 -- 
+ attr: name (v/c), color (v/c)

However, when I print the values for the attribute it turns out they are not there:

> toy.graph$color
NULL

What am I missing?

EDIT The solution with assigning y works perfect when I have just one color. However, I still have issues when I want to assign multiple colors within each switch options. Here is my attempt with the y assignment:

V(toy.graph)$gender <- sample(c("M","F"), 6, replace = TRUE)
V(toy.graph)$gender
[1] "M" "F" "F" "M" "F" "M"

deco2 <- function(x, lev){
         y <- switch(lev,
             one = {V(x)$color = "red"},
             two = {V(x)[gender == "F"]$color = "yellow"
                    V(x)[gender == "M"]$color = "green"})
         V(x)$color <- y
         return(x)
}

For some reason I get assign only the "green" color:

toy.graph <- deco2(toy.graph, lev="two")
toy.graph
IGRAPH UN-- 6 5 -- 
+ attr: name (v/c), gender (v/c), color (v/c)
V(toy.graph)$color
[1] "green" "green" "green" "green" "green" "green"
1

There are 1 best solutions below

1
On BEST ANSWER

This looks like what you want:

library(igraph)
toy.graph <- graph.formula(121-221,121-345,121-587,345-587,221-587,490,588)

deco2 <- function(x, lev){
  #make sure you assign switch's output to a variable (e.g. y)
  y <-
  switch(lev,
         one =  "red",
         two =  "yellow")
  V(x)$color <- y
  x
}


toy.graph <- deco2(toy.graph, lev="one")

> V(toy.graph)$color
[1] "red" "red" "red" "red" "red" "red"

I don't think it is a good idea to assign a value to x inside switch. Instead use switch for what it has been designed i.e. to return the value corresponding to your input and then in the next step assign that value to your object.

This way it works as expected!