23  Functions

Functions are the vocabulary of R. They are pre-written scripts that perform specific tasks, saving you the effort of rewriting common procedures. Just like using the right word in a sentence, using the right function is key to an efficient and effective R program. Think of each function as a tool in your toolbox. The more tools you have and know how to use, the easier it will be to solve programming challenges. We have already mastered many functions for a variety of tasks. Now, our focus will shift to learning how to craft our own tools.

To create custom functions in R, follow this function structure:

function_name <- function(input) {
  # Do something
  return(output)
}

For example,

# create a function to calculate squared values
getSquare <- function(x) {
  squared <- x * x
  return(squared)
}

Let us write a function that calculates the area of a rectangle. This function will require two arguments: the length and the width of the rectangle.

# create a function to calculate area
calculateArea <- function(length, width) {
  area <- length * width
  return(area)
}

In this function named calculateArea, we have two parameters: length and width. We calculate the area by multiplying these two parameters and then return the result.

You can use this function by passing the length and width values as arguments:

rect_area <- calculateArea(5, 3)
print(rect_area)
[1] 15

Exercise A

Q1

Write a function that performs addition on two variables. Test it with the input values \(3\) and \(9\).

Q2

Write a ‘greet’ function that welcomes a user by a specified name. It should return a message like, “Welcome, Amy!” Use the structure provided below.

greetSomeone <- function(name = "user") {
  ## enter your code here
}
# you can test it by
# greetSomeone("Amy")
# greetSomeone("Bob")