2.5 Functions
Before we move onto data structures in the next section, we will take an aside to look at functions. Functions are a group of commands that perform a specific action. By itself it is not a complete executable program but form part of a larger workflow. Like variables that hold data, functions are also given a name so that they can be reused. They generally follow the \(input \rightarrow process \rightarrow output\) model, that is, they take input, do something with the input and produce output. The output can either be printed to the screen or be returned and assigned to a variable that holds the new data for further reuse.
So far we have already started using some of the in-built functions in R like print()
, str()
, as.integer()
etc. They take the form of output_variable <- function_name(input_variable)
where the output_variable is optional. If not output_variable is provided, by default the output from the funciton will be printed to the screen.
2.5.1 Nesting functions
Other than assigning the output of a function to a variable, functions can also be nested within other functions. For example, the following code performs an operation and prints the result to the screen:
length <- 42
width <- 10
area <- length*width
result <- paste("area of rectangle with length=",length,
", width=", width, "is", area)
print(result)
can be collapsed to:
print(paste("area of rectangle with length=",length,
", width=", width, "is", length*width))
## [1] "area of rectangle with length= 42 , width= 10 is 420"
Just like in mathematics, the order of operations (or operator precedence) is the same in R. Operations are evaluated (or executed) from the innermost brackets first. So in the command above, the inner c("A","B","C")
is executed first and the output (which is held temporarily in memory) is then passed to the outer function paste()
.
With this shortcut, you can reduce the resources that a program takes (not to mention the lines of code) and create very complex nested function calls. Keep an eye out for nested functions throughout the workshop.
Break it up first, then reassemble
When new to R and coming across a complex nested function call, the tip is to break it up into sections. Break the functions into smaller pieces starting from the innermost function and assign them to variables first. Execute each line, one at a time and examine the output. Then when you are comfortable with what each line is doing, put the pieces together again. This will help you understand what each function is doing first before trying to decipher the entire line in one go. Once you become familiar with more functions, reading nested functions will become a breeze!