Chapter 5 Functions

5.1 Tutorial Video

R Functions

Card image

R Functions

GO!

18-Mar-2021

5.2 Reference

Functions

You’ll learn functions in R programming; how to create them, why it is used and so on.

Functions in general can be categorized into 3 types

  1. Primitive functions
  2. Pre-built functions
  3. User defined functions

No matter what the type it is, a function is a block of code which executes when it is called. Calling a function is simple task. Just write the name of the function and then the data you want the function to operate on in parentheses. A function can return data as a result. For example, running a c function c(1,2) to combine two values into a vector. The returned the value is a numeric vector 1 2.

The function is created by the following steps in order:

  1. The keyword function always must be followed by parentheses. It tells R that what comes next is a function.
  2. The parentheses after function form the argument list, of your function. Between the parentheses, the arguments to the function are given. The number of the argument could be zero
  3. The braces, {}, everything between the braces is part of the body of your function.

  4. The return() statement is to returned the object from inside the function to your R GUI/workspace. Usually return() can be omitted with care.
  5. You should get a complete function by now. Usually, you want to name your function by using the assignment operator <- or equal sign = to put this complete function into a variable (R naming convention applied here).

The summary: R functions is to incorporate sets of instructions that you want to use repeatedly, because of their complexity, are better self-contained in a sub program and called when needed. A function is a piece of code written to carry out a specified task; it can or can not accept arguments or parameters and it can or can not return one or more values.

R Functions Exercises (optional)

Exercise 1

Can you revise the function named “sum_of_rounded_numbers” mentioned in the video tutorial, so that users can decide how many decimal places they like by giving a numeric value to the third augment?

Exercise 2

Try the below code in your R GUI, what is the error message and why, can you fix it?

  
>  f <- function(a, b) {
+         print(a)
+         print(b)
+ }
> f(45)