Geospatial Modelling Environment

for loop

A programming device that allows you to repeat a set of commands many times


A for loop is a programming device that allows you to repeat a set of commands many times with only a few lines of code. The format of the for loop in this software is similar to that of R. The word ‘for’ indicates that you are starting a loop. The next expression controls the number of iterations: for(i in 1:100) implies that the loop is going to repeat itself 100 times. The letter ‘i’ is the index variable name – it could be any simple string you wish to use (another letter, or even a text string like ‘num’). You can use this variable in subsequent commands to construct command arguments using the paste() function.

The set of commands that are to be repeated must be contained between one set of braces { }, and each command must end with a semi-colon to distinguish it from the next command. Nested for loops are supported, but it is essential to use a different index variable for each nested loop (e.g. i, j, k for three nested loops). For loops can be included within scripts that you call with the ‘run’ command.

An advanced problem is building the for(i in 1:100) statement using dynamic variables. For instance, rather than specify 1 and 100, you might want to use variables you have previously defined (see ‘Strategic commands, functions and clauses’ section). This is possible, however: you must ensure the variables are defined (and visible using the ls() command) prior to submitting the for loop command text. I.e. you cannot define the variables and use them in a for loop in the same block of text that is submitted to GME. This is a command interpreter limitation that I intend to resolve in a future update. This should not be a limitation to the majority of users.

See also: paste, r.eval


for(i in 1:100) { commands }

ithe variable name (can be any simple string)
1:1000the range of values that will be iterated through, incrementing +1 at each step
{commands}the braces contain the list of commands that will be repeated; each command must be separated by a semi-colon


for(i in 1:5) {

genrandompnts(poly=”C:datafields.shp”, sample=100, out=paste(“C:datasamples”, i, “.shp”));

addxy(in=paste(“C:datasamples”, i, “.shp”), prefix=”COORD”);

r.plotxy(in=paste(“C:datasamples”, i, “.shp”, xfield=”COORDX”, yfield=”COORDY”);


Results in the generation of 5 point datasets, with COORDX, COORDY fields in the attribute table, and five R graphs of the x, y coordinates.


Please consider making a purchase to support the continued development of these tools  Read more...

Tips on how to use this interface efficiently 


Open Source GIS

Copyright © 2001-2014 Hawthorne L. Beyer, Ph.D., Spatial Ecology LLC    Connect on LinkedIn