20  Writing Functions and Packages

Overview

In this chapter of Essential R, we’ll take a look at writing functions, debugging them, and also at the creation of packages.

Objectives

Upon completion of this lesson, you should be able to:


  1. Write simple functions with default arguments
  2. Control how values are returned by your function
  3. Debug a function
  4. Recognize and prevent some common errors in user-created functions
  5. Create a simple package

Data and R Code Files

The R code file and data files for this lesson can be found on the Essential R - Notes on learning R page.

R logo

20.1 Creating a Function

Here we’ll demonstrate the most basic creation of a function using the function function ().

Video - STAT 485 Lesson: 20.1

20.2 Specifying Default Values for Arguments

Now we’ll consider how default values for arguments are specified. Also, we’ll discuss how functions are evaluated (hint: not in user workspace).

Video - STAT 485 Lesson: 20.2

20.3 Returning Values

In this video, we’ll consider how to return single or multiple values from a function.

Video - STAT 485 Lesson: 20.3

20.4 Functions that Change Objects Are Risky

In this video I will try to convince you that it is probably not a good idea to write functions that change objects in your environment, but then I will show you how to do it anyway, and duscuss under what (rare) circumstances it might make sense to do this.

Video - STAT 485 Lesson: 20.4

20.5 Debugging Errors and Checking Inputs

Here we will discuss debugging errors and checking inputs when a function is called.

Video - STAT 485 Lesson: 20.5

20.6 Sneaky Errors - NA Values

We’ll conclude our discussion of writing functions by considering how NA values may affect functions.

Video - STAT 485 Lesson: 20.6

20.7 Creating a Package Part I

Now we’ll consider why you might want to create a package, and how you would go about doing so.

Video - STAT 485 Lesson: 20.7

20.8 Creating a Package Part II

We’ll conclude this lesson by finishing our demonstration on package creation.

Video - STAT 485 Lesson: 20.8