使用 R 中的函数分配图形属性
Assigning graph attributes using a function in R
我正在研究一组函数,这些函数可以让我以各种方式绘制网络数据。因为一些过程被用于多个函数,为了避免复制和粘贴,我尝试把这些过程变成迷你函数,这样我就可以在需要的时候简单地回忆起来。
现在我遇到了一个迷你函数,它会根据属性装饰我的图表。例如,我希望能够绘制图表
toy.graph <- graph.formula(121-221,121-345,121-587,345-587,221-587, 490, 588)
并为其指定颜色。但是当我尝试使用以下功能时:
deco <- function(x){
V(x)$color <- "red"
}
并将其应用到我的图形中,但未添加颜色:
deco(toy.graph)
toy.graph
## IGRAPH UN-- 5 5 --
## attr: name (v/c)
V(toy.graph)$color
## NULL
我错过了什么?
两件事:
- 你的函数不是return值。
- 您在调用函数时并未重新分配变量。
尝试:
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)
如果你想避免重新分配变量并让你的函数 return 有一个值,你可以在你的函数内部使用 eval
来计算父环境中的 V(x)$color <- "red"
。
编辑 有趣的环境:
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)
我正在研究一组函数,这些函数可以让我以各种方式绘制网络数据。因为一些过程被用于多个函数,为了避免复制和粘贴,我尝试把这些过程变成迷你函数,这样我就可以在需要的时候简单地回忆起来。
现在我遇到了一个迷你函数,它会根据属性装饰我的图表。例如,我希望能够绘制图表
toy.graph <- graph.formula(121-221,121-345,121-587,345-587,221-587, 490, 588)
并为其指定颜色。但是当我尝试使用以下功能时:
deco <- function(x){
V(x)$color <- "red"
}
并将其应用到我的图形中,但未添加颜色:
deco(toy.graph)
toy.graph
## IGRAPH UN-- 5 5 --
## attr: name (v/c)
V(toy.graph)$color
## NULL
我错过了什么?
两件事:
- 你的函数不是return值。
- 您在调用函数时并未重新分配变量。
尝试:
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)
如果你想避免重新分配变量并让你的函数 return 有一个值,你可以在你的函数内部使用 eval
来计算父环境中的 V(x)$color <- "red"
。
编辑 有趣的环境:
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)