Conditionals & Loops

# A conditional is a piece of code that only gets evaluated if a certain
# condition is true:

a = 5

if (a < 2) {
    print("a is smaller than 2")
}

if (a < 2) {
    print("a is smaller than 2")
} else if (a > 2) {
    print("a is larger than 2")
}
## [1] "a is larger than 2"
if (a == 2) {
    print("a equals 2")
} else if (a == 3) {
    print("a does not equal 2 but 3")
} else {
    print("a neither equals 2 nor 3")
}
## [1] "a neither equals 2 nor 3"
# A for loop is a chunk of code that gets executed many times, each time for a
# different value of a so-called 'index-variable', named 'ii' in the following.
# It is useful if you need to repeat a procedure for, say, different countries
# in your data sample.

a = 0
for (ii in 1:10) {
    a = a + ii
}
print(a)
## [1] 55
for (ii in c("a", "b")) {
    print(ii)
}
## [1] "a"
## [1] "b"
# Note that 1:10 and ' c('a','b') ' are both vectors.  We can also use the othe
# ways to create vectors from above, e.g.:
for (ii in seq(-3, 3, by = 1.5)) {
    print(ii)
}
## [1] -3
## [1] -1.5
## [1] 0
## [1] 1.5
## [1] 3
# A while loop keeps executing a chunk of code only as long as some condition
# is true:

while (a < 130) {
    a = a + 3
}
print(a)
## [1] 130
# Useful commands for working with for- and while-loops are 'next' and
# 'break()'.  The former tells R to stop executing the code for the current
# iteration and proceed to the next one, while the latter tells R to stop the
# for- or while-loop altogether.


a = 0
for (ii in 1:10) {
    if (ii%%2 == 0) {
        # if ii is even (modulus of ii/2 is null), go to next iteration (i.e.
        # skip this one)
        next
    }
    a = a + ii
}
print(a)
## [1] 25
while (a < 130) {
    a = a + 3

    if (a == 88 | a == 89) {
        (break)()
    }

}
print(a)
## [1] 88