[R] Equivalent to go-to statement

Gabor Grothendieck ggrothendieck at gmail.com
Sun Jul 25 08:43:24 CEST 2010


On Sun, Jul 25, 2010 at 1:57 AM, Michael Haenlein
<haenlein at escpeurope.eu> wrote:
> Dear all,
>
> I'm working with a code that consists of two parts: In Part 1 I'm generating
> a random graph using the igraph library (which represents the relationships
> between different nodes) and a vector (which represents a certain
> characteristic for each node):
>
> library(igraph)
> g <- watts.strogatz.game(1,100,5,0.05)
> z <- rlnorm(100,0,1)
>
> In Part 2 I'm iteratively changing the elements of z in order to reach a
> certain value of a certain target variable. I'm doing this using a while
> statement:
>
> while (target_variable < threshold) {## adapt z}
>
> The problem is that in some rare cases this iterative procedure can take
> very long (a couple of million of iterations), depending on the specific
> structure of the graph generated in Part 1. I therefore would like to change
> Part 2 of my code in the sense that once a certain threshold number of
> iterations has been achieved, the iterative process in Part 2 stops and goes
> back to Part 1 to generate a new graph structure. So my idea is as follows:
>
> - Run Part 1 and generate g and z
> - Run Part 2 and iteratively modify z to maximize the target variable
> - If Part 2 can be obtained in less than X steps, then go to Part 3
> - If Part 2 takes more than X steps then go back to Part 1 and start again
>
> I think that R does not have a function like "go-to" or "go-back".
>
> Does anybody know of a convenient way of doing this?
>
> Thanks very much for your help,
>

goto's can be replaced with loops.  In this case create a double loop
such that the outer loop does not repeat if the inner loop finished
due to reaching the target:

target_variable <- -Inf
while(target_variable < threshold) {
        ...
        iter <- 0
        while(target_variable < threshold && iter < max_iter) {
           ... update iter and target_variable ...
        }
}



More information about the R-help mailing list