9  R: Functions

9.1 Defining a function

Functions in R are defined using the keyword function(). All the statements within a function are enclosed with {} braces. Look at the function defined below. It takes an integer as an argument, and prints whether the integer is odd or even.

odd_even <- function(intgr) {
  if (intgr %% 2 == 0) {
    print("even")
  } else {
      print("odd")
  }
}

odd_even(3)
[1] "odd"

9.1.1 Practice exercise

Write a function that returns all prime numbers between \(a\) and \(b\), where \(a\) and \(b\) are parameters of the function.

prime <- function(a, b) {
  prime_numbers <- c()
  for (number in a:b) {
    prime = 1
    
    for (factor in 2:(number - 1)) {
      if (number %% factor == 0) {
        prime = 0
      }
    }
    
    if (prime == 1) prime_numbers <- c(prime_numbers, number)
  }
  return(prime_numbers)
}
prime(40, 60)
[1] 41 43 47 53 59