Figuring out functions

Note: You can run selected lines of R code by pressing CTRL-Enter after selecting them.

Quick Answers

Notes:

  • Replace anything starting with my with names meaningful to your analysis.
  • You can have zero or more arguments(inputs) to your function
  • To return more than one object, put them in a list then return the list.

What is a function?

A function is block of R code can be stored in an object, and can then be run using the name of the object. Functions can be given zero or more R objects to use when running the code block.

Running a function is often referred to as “calling the function”. E.g. “You can perform linear regression by calling the lm() function.”

Examples of common functions in R include mean(), lm(), and summary().

Parts of a function

A function has two core parts: its argument list (technically called its formals) and its body.

  • The argument list contains a list of objects (usually data) that will be made available to the function when it is called.
  • The body of a function contains the code that the function will run. This is usually one or more R expressions, typically followed by a return() statement.

Here are three examples:

Function Part: Argument list

Arguments are the objects that are provided to a function so that it can perform some action using them. There are several important things to know about these arguments.

  • Functions can many arguments, or they can have an empty argument list.
  • Function arguments have names.
  • Function arguments can have default values.
  • Function arguments have a specific order.

Argument Length

Argument names

There are four important things to understand about the names of function arguments:

  • To use a named argument when calling a function, put the argument name, and equals sign “=”, and then the object/value.
  • Function arguments names lets you rearrange the order of arguments when calling a function.
  • Function argument names are not required when calling a function unless you are rearranging the argument order.
  • The function arguments in the argument list only exist inside the function.

Function Part: Body

Exercise Set 1: Simple functions

Now try turning the following expressions into simple functions: