Changing list by reference in R

1

I have the following problem. I have 5 graphs (per hour, it will not matter the structure of each graph, only I have 5 graphs) and put them inside a list in R. I will make changes in these graphs within a loop that will have 100 loops.

Example:

for (i in 1:100){

for(vile in viles){

  if(sample(1:10,1) <= 1){ # Aresta interna aparecer
    graphInverse <- graph.full(6,directed = TRUE) - vile;
    allEdgesInverse <- get.edgelist(graphInverse);
    randomEdge <- sample(1:length(allEdgesInverse[,1]),1);

    if(length(allEdgesInverse[,1]) != 0){ # Se o grafo nao for completo.
      vile[allEdgesInverse[randomEdge,][1],allEdgesInverse[randomEdge,][2]] <- 1;
    }

  }
  if(sample(1:10,1) <= 1){ # Aresta interna desaparecer
      allEdges <- get.edgelist(vile); 
      randomEdge <- sample(1:length(allEdges[,1]),1);
      vile[allEdges[randomEdge,][1],allEdges[randomEdge,][2]] <- NULL #Vertice deletado
  }

}

}

In the first condition, I enter a random edge with probability 0.1 that did not exist, already in the second condition, I exclude an existing edge with the same probability. This previous explanation is just for contextualizing. My problem is, at each loop (from the first for) it starts a new loop in the 'viles' list (where it contains all my 5 graphs), I make the appropriate changes, but my 'viles' list is updated, or either in the next loop, of the variable 'i', my list is unchanged, that is, the values are still the initials. I am altering by value, not by reference. Could someone help me find a data structure that, once I change the village, the structure that holds that village is updated with that new village changed or changed by reference, rather than value.

    
asked by anonymous 17.10.2016 / 14:03

1 answer

0

When you make a for of the form for(i in x) , R makes a copy of the x object and does not change it at each iteration.

A simple example is:

> x <- list(a = 1, b =1)
> for(i in x){
+   i <- i + 1
+ }
> x
$a
[1] 1

$b
[1] 1

> x <- list(a = 1, b =1)
> for(i in 1:length(x)){
+   x[[i]] <- x[[i]] + 1
+ }
> x
$a
[1] 2

$b
[1] 2

The right way to do it is:

for(j in 1:length(viles)){

  if(sample(1:10,1) <= 1){ # Aresta interna aparecer
    graphInverse <- graph.full(6,directed = TRUE) - viles[[j]];
    allEdgesInverse <- get.edgelist(graphInverse);
    randomEdge <- sample(1:length(allEdgesInverse[,1]),1);

    if(length(allEdgesInverse[,1]) != 0){ # Se o grafo nao for completo.
      viles[[j]][allEdgesInverse[randomEdge,][1],allEdgesInverse[randomEdge,][2]] <- 1;
    }

  }
  if(sample(1:10,1) <= 1){ # Aresta interna desaparecer
      allEdges <- get.edgelist(viles[[j]]); 
      randomEdge <- sample(1:length(allEdges[,1]),1);
      viles[[j]][allEdges[randomEdge,][1],allEdges[randomEdge,][2]] <- NULL #Vertice deletado
  }

}

Note that I have changed all references to vile , viles[[j]] , and change the vector traveled by the loop.

    
17.10.2016 / 19:55