Functions in R (Chapter 1 Episode 7)

A function is simply a set of statements that have been put together for the purpose of performing a specific task. With functions, a code can be broken into simpler parts which are easy to understand and maintain. R comes with many in-built functions. It also allows its users to create their own functions.

Function Definition

function_name <- function(argument_1, argument_2, ...) { 
Function body }

The following are the different parts of the function:

  • function_name : this is the actual name of the function. It is stored as an object with that name in the R environment.

  • Arguments: this is just a placeholder. Once the function has been invoked, a value will be passed to the argument. The arguments can have default values, but arguments are optional in a function since functions can be used without arguments.

  • Function Body: this is a collection of statements that define what the function will do.

  • Return value- this is the last expression in our function body which is to be evaluated.

Case Use without Parameter

greeting <- function(){
  print('Hello World')
}

output

> greeting()
[1] "Hello World"

Case Use with Parameter


square_num <- function(num){
  resultnum = num * num
  return(resultnum)
}
square_num(2)

output

> square_num(2)
[1] 4

Variable Scope

The scope of a variable determines the place within a program from which it can be accessed. The scope of a function is determined by the place of a declaration of the variable in relation to the function, that is, whether inside or outside the function. There are two types of variables based on scope in R:

  • Global Variable

  • Local Variable

Global Variable

A global variable is a type of a variable that will exist throughout the execution of a program. A global variable can be accessed and modified from any section of the program. However, a global variable will also depend on the perspective of a function

mylist  <- list(FALSE, TRUE, c(1,2,3,4), 'Ruqy')
print(mylist)

In the above code, the variable name mylist is a global variable

Local Variable

Although a global variable exists throughout the execution of the program, a local variable exists only within a particular part of a program such as a function and it will be released after the end of the function call. Let us use our previous example to demonstrate how a local variable works

square_num <- function(num){
  result = num * num
  return(result)
}

In the above code, return is a local variable as it only exists in the function scope.