Much like other languages, R has a set of control structures.  Namely:

  • If / else (if a condition is met, do something)
  • For (loop for x number of times)
  • While (while something is true, loop)
  • Repeat (infinite loop)
  • Break (exit a loop)
  • Next (skip an iteration of a loop)
  • Return (exit a function)

IF

If you are familiar with Java or Groovy, the R if statement looks the same:

if(some condition){
   run some logic
}else{
   run some logic
}

You can set a variable to an entire if/else block by doing:

y <- if(x = 3){
  x/2
}

FOR

for(i in 1:10){
   do something
}

this iterates through a sequence.

Here’s another example:

x <- c(“a”,”b”,”c”,”d”)

for(letter in x){
    print(letter)
}

WHILE

While loops are just like in other languages….

x <- 0

while(x < 10){
   print x
   x <- x + 1
}

REPEAT

This was  new concept for me. In this case you call an infinite loop.  It can only end when you break from it.  For example:

repeat{
   some block of code
   if(some condition){
       break
   }
}

NEXT

Next was also a concept I wasn’t familiar with. In this case you are skipping the loop block for an iteration(s.)  Here’s an example:

for(i in 1:50){
   if(i <= 25){
       next
   }
   do some code here
}

In the above example, the first 25 iterations of the loop are skipped.  After the 25th iteration it exits the if statement and runs the block of code that could be there.

Leave a Reply

Your email address will not be published. Required fields are marked *