Elements of programming

Programming and Data Analysis with R

Author
Affiliation

Tommaso Rigon

UniversitĂ  degli Studi di Milano-Bicocca

Homepage

Unit B

  • Defining a new function
  • Control statements: if, else
  • for loops, while loops
NoteNote

The exercises associated with this unit are available at this link.

Functions I

Besides being a statistical software, R is a programming language.

In R, functions are objects like any other. Indeed:

class(sum) # Identifies the type of object
[1] "function"
class(log) # Second example
[1] "function"

It is therefore possible to define new functions, in addition to the ones that already exist.

Once created, functions can be used exactly like all the others.

Functions II

To create a new function, one uses the command function.

The new function cube computes the cube of the number it receives as input:

cube <- function(x) {
  out <- x^3
  out
}

The last object (in this case called out) is returned as the result:

cube(4) # Computes the cube of the value 4
[1] 64

Alternatively, we can also use the command return to return the result:

cube <- function(x) {
  out <- x^3
  return(out) # Makes it explicit that the value to be returned is out
}
cube(8) # Computes the cube of the value 8
[1] 512

Functions III

It is possible to define new functions with multiple arguments, also choosing their default values

power <- function(x, p = 2) {
  out <- x^p
  out
}

The default value for the argument p is the square (p = 2), indeed:

power(x = 4) # Computes the square of the value 4
[1] 16
power(4) # Alternative syntax: the argument names need not be specified
[1] 16

However, we can select a different power as follows:

power(x = 4, p = 3) # Computes the cube of the value 4
[1] 64
power(4, 3) # Alternative syntax: the argument names need not be specified
[1] 64

Control statements I

The control statement if makes it possible to perform a given operation only if a certain condition is satisfied (TRUE or FALSE).

The (optional) control statement else makes it possible to perform an alternative operation if the previous condition is not satisfied.

For example, the following code prints on screen (function print) a different sentence depending on whether the condition is true or false:

condition <- pi^2 < 10 # Boolean value (in this case the condition is TRUE)

if (condition) {
  print("The condition is true")
  # Some commands to be executed
  # ...
} else {
  print("The condition is false")
  # Other commands to be executed
  # ...
}
[1] "The condition is true"

Control statements II

The following function square_root is a more concrete example concerning if and else.

If the number provided as input is negative, a NaN is returned:

square_root <- function(x) {
  if (x < 0) {
    # Warning message; it would actually be more appropriate to use "warning"
    print("The value of x must be non-negative")
    out <- NaN # Return Not A Number
  } else {
    out <- sqrt(x)
  }
  out
}

square_root(-2) # The condition x < 0 is satisfied
[1] "The value of x must be non-negative"
[1] NaN
square_root(36) # The condition x < 0 is NOT satisfied
[1] 6

while and for loops I

for loops and while loops repeat the operation contained between the curly brackets { }: while loops as long as a given condition is satisfied, for loops once for each value of a vector.

Let us start with a simple example concerning the while function:

i <- 5 # We start with i = 5

while (i <= 25) { # Repeats the operation as long as i is smaller or equal to 25
  print(i) # Prints on screen the value of i
  i <- i + 5 # Increases the value of i

  # In real settings, here there are of course other operations to be executed
  # ...
}
[1] 5
[1] 10
[1] 15
[1] 20
[1] 25

while and for loops II

Be careful not to create endless loops!

The following code requires a forced interruption of the R session or, in the worst case, a restart of the computer:

# DO NOT RUN THE FOLLOWING CODE!
#
# The condition i <= 25 is always true because i is never updated
i <- 5
while (i <= 25) {
  print(i)

  # Other operations to be executed
  # ...
}

while and for loops III

As an alternative to while loops, one can use the more explicit syntax of for loops.

The for loop executes the content of the curly brackets considering, one at a time, the values contained for instance in a vector:

values <- seq(from = 5, to = 25, by = 5)
values
[1]  5 10 15 20 25
for (i in values) {
  print(i + 2) # Prints on screen the value of i + 2

  # Other operations to be executed
  # ...
}
[1] 7
[1] 12
[1] 17
[1] 22
[1] 27