Assigning graph attributes using a function in R

主宰稳场 提交于 2019-12-08 09:46:08

问题


I am working on a set of functions that will allow me to plot network data in various ways. Because some procedures are being used in multiple functions, to avoid copying and pasting I try to turn such procedures into mini-function that I can then simply recall whenever necessary.

Right now I got stuck with a mini-function that would decorate my graph based on attributes. For example I want be able to take a graph

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

and assign to it color. But when I try to use the following function:

deco <- function(x){
        V(x)$color <- "red"
}

and apply it to my graph the color is not being added:

deco(toy.graph)
toy.graph
## IGRAPH UN-- 5 5 -- 
## attr: name (v/c)

V(toy.graph)$color
## NULL

What am I missing?


回答1:


Two things:

  1. Your function is not returning a value.
  2. You aren't reassigning the variable when you call the function.

Try:

toy.graph <- graph.formula(121-221,121-345,121-587,345-587,221-587, 490, 587)
deco <- function(x){
        V(x)$color <- "red"
        return(x)
}
toy.graph <- deco(toy.graph)
plot(toy.graph)

If you want to avoid reassigning variables and having your function return a value, you can probably use eval inside your function to evaluate V(x)$color <- "red" in the parent environment.

EDIT fun with environments:

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

deco <- function(x) {
  # get actual variable name
  p = deparse(eval(substitute(substitute(x)), parent.frame())) 
  # create expression to evaluate
  e = parse(text = paste0("V(", p, ")$color <- 'red'"))
  # evaluate in parent environment
  eval.parent(e)
}

deco(toy.graph)
plot(toy.graph)


来源:https://stackoverflow.com/questions/29853814/assigning-graph-attributes-using-a-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!