Introduction to functions

Exercises: function introduction

Function structure

Learning goal: Identify the structure of functions in terms of inputs, arguments, return objects and naming.

Instruction: Pick three functions of your choice and note their characteristics. (pairs)

For example:

  • name
  • arguments (inputs, options)
  • return object (outputs)

Feel free to look up documentation online, in the R help manual on your computer through RStudio or using the ? and ?? commands.

We encourage you to find your own functions, maybe a function you use or have wanted to learn about. If you can’t think of any right now, see for example stats::lm(), stats::runif(), or (trickier) base::do.call().

Thinking in functions

Instruction: For the following tasks, write a function’s name, arguments and return object. Do this on paper, or in a blank text document - we are not writing code yet.

First round (solo)

  • Count the number of values greater than 0 in one column of a data.frame
  • Filter rows in one column of a data.frame that match a string
  • Plot a histogram for each vector of numbers in a list

Learning goal: Reframe how we might think of code for an analysis as a series of steps instead as inputs, outputs, and arguments of functions.

Second round (together)

  • Aggregate columns of a data.frame by a grouping column, calculate a metric, and make two summary plots
  • Print summary statistics, make a diagnostic plot, filter based on an input argument, and write out a spreadsheet

Learning goal: identify when a function’s goal is too complex and could be split into subfunctions that are easier to develop and test.

Reading functions

Instruction: Read the following functions and note what you expect they will output. We have purposely used vague function names in this case - not our typical recommendation! When you are ready, click “Show output”.

Function 1

apple <- 'green'

f <- function(x) {
  nchar(x)
}

f(apple)
Show output
[1] 5

Function 2

apple <- 'gala'

f <- function(x, times) {
  rep(x, times = times)
}

f(apple, 10)
Show output
 [1] "gala" "gala" "gala" "gala" "gala" "gala" "gala" "gala" "gala" "gala"

Function 3

apple <- 'mcintosh'
potato <- 'russet'

f <- function(apple, potato) {
  data.frame(apples = apple, potatoes = potato)
}

f(potato = potato)
Show output
Error in f(potato = potato): argument "apple" is missing, with no default