问题
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:
- Your function is not returning a value.
- 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