L4: Functions and Loops

Bogdan G. Popescu

John Cabot University

Functions

A function is a block of code which only runs when it is called.

You can pass data, known as arguments, into a function.

A function can return data as a result.

Functions

Functions

Functions

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before:

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before

x = -5
if (x > 0) {
  print('x is positive!')
} else {
  print('x is negative or zero!')
}
[1] "x is negative or zero!"

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before

x = -5
if (x > 0) {
  print('x is positive!')
} else {
  print('x is negative or zero!')
}
[1] "x is negative or zero!"

This is how we write this as a function called is_this_no_positive

is_this_no_positive<-function(x)

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before

x = -5
if (x > 0) {
  print('x is positive!')
} else {
  print('x is negative or zero!')
}
[1] "x is negative or zero!"

This is how we write this as a function called is_this_no_positive

is_this_no_positive<-function(x) {
  if(x > 0)

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before

x = -5
if (x > 0) {
  print('x is positive!')
} else {
  print('x is negative or zero!')
}
[1] "x is negative or zero!"

This is how we write this as a function called is_this_no_positive

is_this_no_positive<-function(x) {
  if(x > 0) {
    message <- 'x is positive!'
    }

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before

x = -5
if (x > 0) {
  print('x is positive!')
} else {
  print('x is negative or zero!')
}
[1] "x is negative or zero!"

This is how we write this as a function called is_this_no_positive

is_this_no_positive<-function(x) {
  if(x > 0) {
    message <- 'x is positive!'
    } else

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before

x = -5
if (x > 0) {
  print('x is positive!')
} else {
  print('x is negative or zero!')
}
[1] "x is negative or zero!"

This is how we write this as a function called is_this_no_positive

is_this_no_positive<-function(x) {
  if (x > 0) {
    message <- 'x is positive!'
    } else {
    message <- 'x is negative or zero!'
  }

Functions Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before

x = -5
if (x > 0) {
  print('x is positive!')
} else {
  print('x is negative or zero!')
}
[1] "x is negative or zero!"

This is how we write this as a function called is_this_no_positive

is_this_no_positive<-function(x) {
  if (x > 0) {
    message <- 'x is positive!'
    } else {
    message <- 'x is negative or zero!'
  }
  return(message)
}

Functions Examples

This is how we use this function:

is_this_no_positive<-function(x) {
  if (x > 0) {
    message <- 'x is positive!'
    } else {
    message <- 'x is negative or zero!'
  }
  return(message)
}
is_this_no_positive(3)

Functions Examples

This is how we use this function:

is_this_no_positive<-function(x) {
  if (x > 0) {
    message <- 'x is positive!'
    } else {
    message <- 'x is negative or zero!'
  }
  return(message)
}
is_this_no_positive(3)

What is the output of this command?

Functions Examples

This is how we use this function:

is_this_no_positive<-function(x) {
  if (x > 0) {
    message <- 'x is positive!'
    } else {
    message <- 'x is negative or zero!'
  }
  return(message)
}
is_this_no_positive(3)
[1] "x is positive!"

What is the output of this command?

Functions Examples

This is how we use this function:

is_this_no_positive<-function(x) {
  if (x > 0) {
    message <- 'x is positive!'
    } else {
    message <- 'x is negative or zero!'
  }
  return(message)
}
is_this_no_positive(-3)

What is the output of this command?

Functions Examples

This is how we use this function:

is_this_no_positive<-function(x) {
  if (x > 0) {
    message <- 'x is positive!'
    } else {
    message <- 'x is negative or zero!'
  }
  return(message)
}
is_this_no_positive(-3)
[1] "x is negative or zero!"

What is the output of this command?

Functions Examples

Let us now create a third condition: x=0

Functions Examples

Let us now create a third codition: x==0

is_this_no_positive<-function(x) {
  if(x > 0) {
    message <- 'x is positive!'
  }

Functions Examples

Let us now create a third codition: x==0

is_this_no_positive<-function(x) {
  if(x > 0) {
    message <- 'x is positive!'
  }
  if(x==0){
    message <- 'x is zero!'
  }

Functions Examples

Let us now create a third codition: x==0

is_this_no_positive<-function(x) {
  if(x > 0) {
    return('x is positive!')
  }
  if(x==0){
    message <- 'x is zero!'
  } else {
    message <-'x is negative or zero!'
  }
  return(message)
}

Functions Examples

Let us now create a third codition: x==0

is_this_no_positive<-function(x) {
  if(x > 0) {
    return('x is positive!')
  }
  if(x==0){
    message <- 'x is zero!'
  } else {
    message <-'x is negative or zero!'
  }
  return(message)
}
is_this_no_positive(0)
[1] "x is zero!"

Functions Examples

Here is another example of a function.

We create a function called add_five that has one parameter x.

The function calculates and returns the sum of x and 5.

add_five <- function(x) {
  x_plus_five <- x + 5
  return(x_plus_five)
}

Functions Examples

add_five <- function(x) {
  x_plus_five <- x + 5
  return(x_plus_five)
}

Here are the elements of the function:

  • A function name ( add_five )
  • The assignment operator ( <- )
  • The function operator ( function )
  • Parameter(s), inside parentheses and separated by commas ( (x) )
  • Curly brackets ({)

Functions Examples

add_five <- function(x) {
  x_plus_five <- x + 5
  return(x_plus_five)
}

Here are the elements of the function:

  • Code (x_plus_five <- x + 5)
  • Returned value ( return(x_plus_five))
  • Curly brackets (})

Functions Examples

The function add_five, can be used to calculate the sum of various numbers and five

# Function definition
add_five <- function(x) {
  x_plus_five <- x + 5
  return(x_plus_five)
}

Here is what happens if we use 5 as a parameter

# Function call, with argument 5
add_five(5)
[1] 10

Here is what happens if we use 77 as a parameter

# Function call, with argument 77
add_five(77)
[1] 82

Functions Examples

We can of course assign the result of a function to an object.

# Function call, with argument 77
x<-add_five(77)
x
[1] 82

We can write the same function in a different way

# Original Function
add_five <- function(x) {
  x_plus_five <- x + 5
  return(x_plus_five)
}
# Version 2
add_five <- function(x) {
  x + 5
}
# Version 3
add_five <- function(x) x + 5

Default arguments

Default arguments can be specified as part of the function definition.

For example, the following definition add_five does not specify a default value for x

Thus, trying to call add_five without passing an argument for x gives an error

add_five <- function(x) x + 5
add_five()
## Error in add_five(): argument "x" is missing, with no default

The following, an alternative definition, does specify the default value of 1 for x

The default value is then used when calling the function without specifying x:

add_five <- function(x = 1) x + 5
add_five()
[1] 6

Default arguments

The following argument will also yield an error

add_five <- function(x) x + 5
add_five("five")
## Error in x + 5: non-numeric argument to binary operator

Exercises with Functions 1

Objectives Write an R script that classifies a given number into one of three categories using a function:

  • Positive: If the number is greater than 0
  • Negative: If the number is less than 0
  • Zero: If the number is exactly 0

Let’s say the number is 3.

Instructions Use a function to classify the number into one of the categories. The output should look like below:

number<-3
[1] "The number is Negative ."
[1] "The number is Positive ."

Exercises with Functions 2

Objective Write an R script that classifies a person into different age groups using a function, based on the following criteria:

  • Child: 0 to 12 years old
  • Teenager: 13 to 19 years old
  • Adult: 20 to 59 years old
  • Senior: 60 years old and above

Let’s say the age is is 15.

Instructions

Use if-else statements to classify the age into one of the age groups within a function.

age<-15
[1] "You are a Teenager."

Exercises with Functions 3

Objective Write an R script that classifies temperatures into different categories using a function based on the following criteria:

  • Cold: Less than 50 degrees Fahrenheit
  • Moderate: 50 to 75 degrees Fahrenheit
  • Warm: 76 to 90 degrees Fahrenheit
  • Hot: More than 90 degrees Fahrenheit

Instructions 1. Use if-else statements within a function to classify the temperature into one of the categories.

temperature<-50
[1] "The temperature is Moderate."

Loops

A loop is used to execute a given code section more than once.

A for loop is composed of:

  • The for keyword
  • The variable name which we assign to the current vector element (symbol)
  • The in keyword
  • The vector we go over (sequence)
  • A code which defines what to do with each element (expression)

Loops

This is the syntax in a for loop

for(symbol in sequence) {
  expressions
}

Loops Example

This is an example of a for loop:

x <-c(1,2,3)

Loops Example

This is an example of a for loop:

x <-c(1,2,3)
x
[1] 1 2 3

Loops Example

This is an example of a for loop:

x <-c(1,2,3)
x

for (i in x)

Loops Example

This is an example of a for loop:

x <-c(1,2,3)
x

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

Loops Example

This is an example of a for loop:

x <-c(1,2,3)
x
[1] 1 2 3
for (i in x) {
  print(i)
}
[1] 1
[1] 2
[1] 3

Loops Example

Here is another example with strings:

Loops Example

Here is another example with strings:

x <-c("one", "two", "three")
x
[1] "one"   "two"   "three"

Loops Example

Here is another example with strings:

x <-c("one", "two", "three")
x
[1] "one"   "two"   "three"
for (i in x) {
  print(i)
}
[1] "one"
[1] "two"
[1] "three"

Loops Example

Here is another example:

Loops Example

Here is another example:

x <-c(1,2,3)

Loops Example

Here is another example:

x <-c(1,2,3)

for (i in x) {
  print(i*2)
}

Loops Example

Here is another example:

x <-c(1,2,3)

for (i in x) {
  print(i*2)
}
[1] 2
[1] 4
[1] 6

Exercises with Loops 1

  1. Create a vector of numbers from 1 to 10.
  2. Use a for loop to iterate through the vector and print each element.
  3. Calculate the square of each element and store it in a new vector.
  4. Print the original vector and the vector containing the squares.

The output should look like below

[1] "1, 1"
[1] "2, 4"
[1] "3, 9"
[1] "4, 16"
[1] "5, 25"
[1] "6, 36"
[1] "7, 49"
[1] "8, 64"
[1] "9, 81"
[1] "10, 100"

Exercises with Loops 2

  1. Create a vector of odd numbers from 1 to 15.
  2. Use a for loop to iterate through the vector and print each element.
  3. Calculate the square root of each element and store it in a new vector.
  4. Print the original vector and the vector containing the square root.

The output should look like below.

[1] "1, 1"
[1] "3, 1.73205080756888"
[1] "5, 2.23606797749979"
[1] "7, 2.64575131106459"
[1] "9, 3"
[1] "11, 3.3166247903554"
[1] "13, 3.60555127546399"
[1] "15, 3.87298334620742"

Exercises with Loops 3

  1. Create a vector of numbers from 1 to 15.
  2. Calculate the square root of each odd element and store it in a new vector.
  3. Print the original vector and the odd vector containing the square roots.
[1] 1
[1] 2
[1] 1.732051
[1] 4
[1] 2.236068
[1] 6
[1] 2.645751
[1] 8
[1] 3
[1] 10
[1] 3.316625
[1] 12
[1] 3.605551
[1] 14
[1] 3.872983

The %in% operator

The %in% operator returns a logical vector indicating the presence of each element of x in y

For example:

The %in% operator

The %in% operator returns a logical vector indicating the presence of each element of x in y

For example:

x <-c(1,2,3)

The %in% operator

The %in% operator returns a logical vector indicating the presence of each element of x in y

For example:

x <-c(1,2,3)
y <-c(1,2,3,4)

The %in% operator

The %in% operator returns a logical vector indicating the presence of each element of x in y

For example:

x <-c(1,2,3)
y <-c(1,2,3,4)
x %in% y

The %in% operator

The %in% operator returns a logical vector indicating the presence of each element of x in y

For example:

x <-c(1,2,3)
y <-c(1,2,3,4)
x %in% y
[1] TRUE TRUE TRUE

Exercise with the %in% operator 1

  1. Create two vectors, one representing even numbers from 1 to 10, and another representing a set of numbers (some of which are even).
  2. Use the %in% operator to identify and print the even numbers from the second vector that are also present in the first vector.
  3. Calculate the square of each identified even number and store it in a new vector.
# Create two vectors
even_numbers <- 2 * (1:5)  # 2, 4, 6, 8, 10
mixed_numbers <- c(3, 6, 8, 9, 12)
[1] 36 64

Exercise with the %in% operator 2

Finding common elements using %in% and a loop

# Create two vectors
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(3, 5, 7, 9, 11)

The output should look like below

[1] 3 5