Looping
You can loop over a set of lines of code by placing the code inside a "while" or "for" loop.
While Loops
While loops will loop until a condition becomes false.
i=0
while(i<100)
{
print(i)
i=i+1
}
For Loops
A for loop will assign a value to each of the values in a sequence sequentially.
N=100
for(i in 1:N)
{
print(i)
}
Looping to evaluate ranges of parameters
One reason to use loops in R is to try different values for parameters.
A simple example would be to take one of our GAM models and try out a range of parameters for the gamma parameter. The code below creates a sequence of gamma values and then uses a loop to try each value of gamma with our model.
Gammas=seq(1,20,by=1) # setup a sequence of values for gamma
AICs=vector() # setup a vector to contain the AIC values
Count=1
while (Count<=length(Gammas)) # go through all the gamma values
{
# the family is gaussian by default but the gamma should be changed from 1 to smooth
GammaValue=Gammas[Count]
TheModel=gam(MaxHt~s(MaxTemp)+s(MinTemp)+s(Precip),data=TheData,gamma=GammaValue)
# get the AIC value and add it to the vector for all AIC values
TheAIC=AIC(TheModel)
AICs=c(AICs,TheAIC)
Count=Count+1 # move to the next gamma value
}
R for Spatial Statistics