Creating and Using Functions in R with Control Structures:

In R, we have seen built in functions like summary(), mean(), etc. Now let’s see how we can write our own functions. Check out Functions, Nested Functions and Recursion in https://www.w3schools.com/r/r_functions.asp

Objective:

Learn how to create and use functions in R, incorporating basic control structures (if, for, while).

Create a function:

Functions are created using the function function

1. No Arguments / No Body Function:

f <- function() {
  # this is an empty function with no arguments or body code
}

class(f) #class
## [1] "function"
f() #what is inside the function?
## NULL

2. Add an Argument:

# Simple function to add two numbers
add_numbers <- function(x, y) {
  return(x +y)
}

# Call the function
add_numbers(3.9, 13.2)
## [1] 17.1
add_numbers(6, 2) #add_function takes two arguments
## [1] 8

3. Using using the ellipsis (…) in the function definition.

The ellipsis allows a function to accept an arbitrary number of arguments.

sum_all <- function(...) {
  sum(...)
}

sum_all(1, 2, 3, 4, 10, 5)  # Sum of all arguments
## [1] 25
multiply_nums <- function(x, y, z) {
  return (x * y * z)
}

multiply_nums(1, 3, 5)
## [1] 15

Using if/else statement

create_power <- function(x, power_type = "square") {
  if (power_type == "square") {
    return(x^2)
    } else if (power_type == "cube") {
      return(x^3)
      } else {
        return("Invalid power type. Use 'square' or 'cube'.")
      }
}

create_power(3, "square")
## [1] 9
create_power(4, "cube")
## [1] 64
create_power(2, "quadruple")
## [1] "Invalid power type. Use 'square' or 'cube'."

5. Using cat()

cat("Square of 5:", create_power(5, "square"), "\n")
## Square of 5: 25
cat("Cube of 5:", create_power(5, "cube"), "\n")
## Cube of 5: 125
cat("Invalid input:", create_power(5, "other"), "\n")
## Invalid input: Invalid power type. Use 'square' or 'cube'.

cat() → concatenate and print to the console (like print(), but without quotes and allows text + variables together).

“” → newline (moves to the next line).

Create a function that tests if the number is Even or Odd (hint: use the remainder rule %%)

evenOrOdd <- function(x) {
  if(x %% 2 == 0) {
    return("Is even")
  }
  else if (x %% 2 != 0) {
    return("Is odd")
  }
  else {
    return("Invalid input")
  }
  
}

cat("The number 5:", evenOrOdd(5), "\n")
## The number 5: Is odd
cat("The number 8:", evenOrOdd(8), "\n")
## The number 8: Is even

Create a function of your choice

guessCorrectNum <- function(x) {
  if(x == runif(1, min = 1, max = 3)) {
    return("You have guessed the right number!")
  }
  else {
    return("Try again")
  }
}

guessCorrectNum(1)
## [1] "Try again"
guessCorrectNum(2)
## [1] "Try again"
guessCorrectNum(3)
## [1] "Try again"

Function with For Loop

sum_even_numbers <- function(n) {
  total <- 0
  for (i in 1:n) {
    if (i %% 2 == 0) {
      total <- total + i
    }
  }
  return(total)
}

sum_even_numbers(10)
## [1] 30

Let’s break it down

The function sum_even_numbersdefines a function that takes one argument, n (the maximum number). Meaning, if you call sum_even_numbers(10), then n = 10, so the function looks at numbers from 1 through 10 and sums the even numbers only (2,4,6,8,10).

We start by setting the total to zero. total is a variable created inside the function. It’s being initialized (set) to 0 at the start. The purpose: to keep a running sum of the even numbers as the loop goes through 1:n. 

for (i in 1:n) is a for statement that loops over every integer from 1 to n.

if (i %% 2 == 0) means “is i divisible by 2?” (i.e., is it an even number?).

total <- total + i, this means if i is even, add it to the running total.

return(total)- After the loop finishes, return the final sum.

Another for loop example

factorial_func <- function(n) {
  result <- 1
  for (i in 1:n) {
    result <- result * i
  }
  return(result)
}

factorial_func(5)  # 5! = 120
## [1] 120

Write an R function called sum_of_squares that takes one argument, n, and uses a for loop to calculate the sum of the squares of all integers from 1 up to n. For example, if n = 5, the function should return 1² + 2² + 3² + 4² + 5² = 55.

sum_of_squares <- function(n) {
  result <- 0
  
  for(i in 1:n) {
    result <- result + (i^2)
  }
  return(result)
}

sum_of_squares(5)
## [1] 55

Function with While Loop

sum_with_while <- function(n) {
  total <- 0
  i <- 1
  
  while (i <= n) {
    total <- total + i   # add current number
    i <- i + 1           # move to next number
  }
  
  return(total)
}

sum_with_while(5)  # 1 + 2 + 3 + 4 + 5 = 15
## [1] 15

Another while loop example:

roll_until_six <- function() {
  roll <- 0
  count <- 0
  
  while (roll != 6) {
    roll <- sample(1:6, 1)   # random number from 1 to 6
    count <- count + 1
    print(paste("Roll", count, ":", roll))
  }
  
  return(paste("Got a 6 after", count, "rolls!"))
}

roll_until_six()
## [1] "Roll 1 : 2"
## [1] "Roll 2 : 5"
## [1] "Roll 3 : 6"
## [1] "Got a 6 after 3 rolls!"

Start with roll = 0. While roll is not 6, keep rolling a random die (sample(1:6, 1)). Count how many rolls it takes. Stop once you hit 6, and report the result.

For loop

While loop

For loop is like saying “Count to 10 and stop.” While loop is like saying “Keep counting until you see a red light — then stop.”

Write a while loop in R that starts with the number 1 and keeps adding numbers together until the total reaches at least 50. Print the final total.

add_nums_while_loop <- function(n) {
  count <- 1
  i <- 1
  
  while(i < n) {
    count <- count + i
    i <- i + 1
  }
  
  return(i)
  
}
  
add_nums_while_loop(50)
## [1] 50

Prompts:

  1. Write a function called add_five that takes a number and returns that number plus 5.
add_five <- function(n) {
  result <- n + 5
  
  return(result)
  
}

add_five(2)
## [1] 7
  1. Write a function check_number that takes a number and returns “Positive” if the number is greater than 0, “Negative” if less than 0, and “Zero” if equal to 0.
check_number <- function(n) {
  if(n > 0) {
    return("Number is positive")
  }
  
  if(n < 0) {
    return("Number is negative")
  }
  
  if(n == 0) {
    return("Number is equal to zero")
  }
  
  
}

check_number(8)
## [1] "Number is positive"
check_number(9)
## [1] "Number is positive"
check_number(-9)
## [1] "Number is negative"
check_number(0)
## [1] "Number is equal to zero"
  1. Write a function sum_of_cubes that uses a for loop to calculate the sum of the cubes of numbers from 1 to n.
sum_of_Cubes <- function(n) {
  result <- 0

  for(i in 1:n) {
    result <- result + (i^3)
  }
  return(result)
}

sum_of_Cubes(5)
## [1] 225
  1. Write a function countdown that uses a while loop to print numbers starting from n down to 1, and then returns “Blast off!”.
countdown <- function(n) {
  
  while(n > 0) {
    print(n)
    n = n - 1
    
    if(n == 0) {
    return("Blast off!")
    }
  }
  
}

countdown(3)
## [1] 3
## [1] 2
## [1] 1
## [1] "Blast off!"