Question

Having trouble with running Breadth-first search algorithm on a graph, my current concern is with the environment parameter, where the callback function is evaluated.

This is the callback function

f.in <- function(graph, data, extra) {
    time <- get.vertex.attribute(graph, "time", index=data["vid"])
    root_time <- get.vertex.attribute(graph, "time", index=extra)
    print(ls(environment()))
    if (time != 0){ 
         time_difference <- time - root_time
         result_list <- c(list(), time_difference)
    }
}

This is the context where the functions is called

graphs <- decompose.graph(network_graph, max.comps = NA, min.vertices = 0) 
lapply(graphs, function(g){
    v0 <- which(degree(g, mode="out") == 0)
    t0 <- get.vertex.attribute(g, "time", index=v0)
    if (t0 != 0) {
         bfs_environment <- new.env()
         assign("result_list", list(), envir=bfs_environment)
         graph.bfs(g, v0, neimode="in", callback=f.in, extra=v0, rho=bfs_environment)
    }
})

Now the print of environment shows me the following variables "data" "extra" "graph" "root_time" "time"

The question is that when I have passed the environment where the callback function is evaluated, then why the "result_list" is not available? Is there something wrong with passing this environment? Btw using R 2.15.3 and iGraph 0.7.0

Was it helpful?

Solution

When the documentation states:

rho: The environment in which the callback function is evaluated

it means that the passed environment is the parent of the callback environment.

So you can retrieve your variable using get() and parent.frame() functions, as shown in the following example:

myCallBack <- function(graph, data, extra) {
  print(ls(parent.frame()))
  print(get('result_list', envir=parent.frame()))
  stop('just to stop at the first call...')
}

# a simple tree with 3 nodes
g <- graph.tree(3, children = 2, mode='out')

bfs_environment <- new.env()
assign("result_list", list(A=3), envir=bfs_environment)

graph.bfs(g, 1, callback=myCallBack, extra=NULL, rho=bfs_environment)

Output:

[1] "result_list"
$A
[1] 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top