14 Functions

14.1 Defining functions

A function can be defined

  • using an identifier (e.g., add_one)
  • on the left of an assignment operator <-
  • followed by the corpus of the function

14.2 Defining functions

The corpus

  • starts with the reserved word function
  • followed by the parameter(s) (e.g., input_value) between simple brackets
  • and the instruction(s) to be executed in a code block
  • the value of the last statement is returned as output

14.3 Defining functions

After being defined, a function can be invoked by specifying the identifier

## [1] 4

14.4 More parameters

  • a function can be defined as having two or more parameters by specifying more than one parameter name (separated by commas) in the function definition
  • a function always take as input as many values as the number of parameters specified in the definition
    • otherwise an error is generated
## [1] 6

14.5 Functions and control structures

Functions can contain both loops and conditional statements in their corpus

## current: 1  | i: 1 
## current: 1  | i: 2 
## current: 2  | i: 3
## [1] 6

14.6 Scope

The scope of a variable is the part of code in which the variable is ``visible’’

In R, variables have a hierarchical scope:

  • a variable defined in a script can be used referred to from within a definition of a function in the same scrip
  • a variable defined within a definition of a function will not be referable from outside the definition
  • scope does not apply to if or loop constructs

14.7 Example

In the case below

  • x_value is global to the function times_x
  • new_value and input_value are local to the function times_x
    • referring to new_value or input_value from outside the definition of times_x would result in an error
## [1] 20