Programming Tools

These are just some of the tools that you might find helpful for the programming challenges in this workbook. This list is by no means exhaustive and you are more than welcome to use any other functions you need to be able to solve the problems.

Operators

You’re already comfortable with most of these operators, so here’s just a quick refresh.

Arithmetic Operators

+ - * / ^

# Addition and subtraction
1 + 1
[1] 2
1 - 1
[1] 0
# Multiplication and division
1 * 2
[1] 2
4 / 2
[1] 2
# Exponents
2 ^ 3
[1] 8

These two are also very useful: %% and %/%

# This operator: %% finds the remainder if you divide two numbers.
# Since 2 goes into 10 evenly, the remainder is 0:
# You'd say that "10 mod 2 is 0:"
10 %% 2
[1] 0
# This operator: %/% does integer division: 3 goes into 10 3 times.
10 %/% 3
[1] 3

Logical Operators

== != > < >= <= & |

# 3 "is equal to" 3
3 == 3
[1] TRUE
# 3 "is not equal to" 2
3 != 2
[1] TRUE
# 3 "is greater than" 2
3 > 2
[1] TRUE
# 3 "is greater than or equal to 2"
3 >= 2
[1] TRUE
# 3 is greater than 2 "AND" 4 modulo 2 is 0:
(3 > 2) & (4 %% 2 == 0)
[1] TRUE
# 3 is greater than 2 "OR" 4 modulo 3 is 0:
(3 > 2) | (4 %% 3 == 0)
[1] TRUE

if/else

Here’s an example of an if statement inside of a function that checks to see if a number x is larger than 3. If it is, it prints a statement.

larger_than_3 <- function(x) {
    if (x > 3) {
        print("This number is larger than 3")
    }
}

larger_than_3(5)
[1] "This number is larger than 3"
# It does nothing if x is not larger than 3.
larger_than_3(2)

You could use an if/else ladder if you wanted there to be more than one condition. You could also have your function return a character string instead of just a side effect of printing it.

sign <- function(x) {
    if (x > 0) {
        return("positive")
    } else if (x == 0) {
        return("zero")
    } else {
        return("negative")
    }
}

sign(5)
[1] "positive"
sign(0)
[1] "zero"
sign(-5)
[1] "negative"

for and while

for loops

The first programmers had only mathematical operators, if for making comparisons, and jump statements that would let them skip sections of code depending on a logical condition. Somewhere along the line, they realized jump statements made code impossible to read and understand. Someone offered a solution: for and while loops. They’re just simple patterns that became really popular because they helped people write clearer programs.

Here’s an example of a for loop inside of a function (with an if statement!). It prints even numbers less than or equal to any number x. It has an iterating variable i that iterates through the sequence 1:x, checking whether the number i is evenly divisible by 2, and if it is, it prints i.

evens_less_than <- function(x) {
    for (i in 1:x) {
        if (i %% 2 == 0) {
            print(i)
        }
    }
}

evens_less_than(10)
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10

while loops

While loops are just like for loops, except instead of iterating through a sequence, they iterate until the logical condition fails to hold. This function prints all the numbers less than a certain number x. It initiates y at 0 and then as long as y continues to be less than x, it keeps on printing y and then adding 1 to y.

numbers_less_than <- function(x) {
    y <- 0
    while(y < x) {
        print(y)
        y <- y + 1
    }
}

numbers_less_than(5)
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4

Other helpful tools

Brackets to select elements from vectors or matrices

If you’re working with a vector, you can use bracket notation to select certain elements of that vector:

# The first element of this vector can be selected using [1]:
c(1, 2, 3)[1]
[1] 1
# The first two elements of this vector can be selected using [1:2]:
c(1, 2, 3)[1:2]
[1] 1 2

Likewise, if you’re working with a 2d data structure like a matrix, you can use bracket notation to select a certain row, column element:

m <- matrix(1:9, nrow = 3)

print(m)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
# Select the first row and first column
m[1, 1]
[1] 1
# Reassign the first row and first column
m[1, 1] <- 10

print(m)
     [,1] [,2] [,3]
[1,]   10    4    7
[2,]    2    5    8
[3,]    3    6    9

$ for extracting a vector from a tibble

You can use $ to take a tibble like gapminder and extract a column vector like lifeExp. l is now a vector:

library(gapminder)

l <- gapminder$lifeExp

l[1:5]
[1] 28.801 30.332 31.997 34.020 36.088