R Object-oriented Programming by Black Kelly;

R Object-oriented Programming by Black Kelly;

Author:Black, Kelly;
Language: eng
Format: epub
Publisher: Packt Publishing


The repeat loop

A repeat loop is used to denote a block of code that will be repeatedly executed until an explicit breakout of the block is executed. The primary advantage of the repeat loop is that the start of the code block will always be executed. One disadvantage is that it can be difficult to read. The syntax is relatively simple:

repeat code block

You must use a break command to tell R to exit the code block. The break command is described in the next subsection in more detail. An example of a repeat loop is given in the following example, and it is a brief example of simulation of a random walk in the complex plane:

positions <- complex(0) # Initialize the history of positions currentPos <- 0.0+0.0i # Start at the origin NUMBERSTEPS <- 50 # Number of steps to take angleFacing <- 0.0 # direction it is facing stdDev <- 1.0 # std dev. of the change in the angle step <- as.integer(0) repeat { ## Update the current time step step <- step + as.integer(1) ## Check to see if it is time to stop if(step>MAXNUMBER) break ## Add new people to the line and update the length angle <- angle + rnorm(1,0.0,stdDev) currentPos <- currentPos + exp(angle*1.0i) positions <- c(positions,currentPos) } plot(Re(positions),Im(positions),type="l")



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.