Loop and conditional structures in R

Conditional structures

IF ... ELSE ...

> if (TRUE) { paste("yes")} else {paste("noo")}

[1] "yes"

Note that the IF statement also works inline:

> Woww = if (TRUE) { paste("yes")} else {paste("noo")}

 

Loop structures

FOR 

Perfect for repeating an operation for a specific number of times.

To end the loop before the end of the iterations, use break (exit the loop) or next (skip iteration)

Basic use:

> for(nbIterations in 1:10) {print("nb",nbIterations)}

[1] "nb"

 

 

[...]

[1] "nb"

 

> Iterator = c("a","b", "c")

> for(i in Iterator) {print(i)}

[1] "a"

[1] "b"

[1] "c"

Use with seq_along function

> for(i in seq_along(Iterator)) {print(Iterator[[i]])}

[1] "a"

[1] "b"

[1] "c"

 

WHILE

When we don't know in advance the right number of iterations.

> # while([condition]) {[execute code]}

REPEAT

When what we need is an inifnite loop, until we decide to get out of the loop with the break instruction.

> i=0;repeat { print(i);i=i+1; if(i>10){break}}

[1] 0

[1] 1

[1] 2

[...]

[1] 9

[1] 10

 

Note the use of the instruction Next here:

 

 

> i=0;repeat {i=i+1; if(i<3){next};  print(i); if(i>10){break}}

[1] 3

[1] 4

[1] 5

[1] 6

[1] 7

[1] 8

[1] 9

[1] 10

[1] 11

Matthieu Liatard
Remember this!
Remember this
Play!
Take a quizz on this subject
Close

Hello :)
At Question-Player, we want to share more knowledge and help you never forget anything ever. And for free.

To show us your support, you can create an account:

Login / Create an account
Rate this article :
1
2
3
4
5

Up next

Related posts