# Lesson 20: Writing Functions and Packages

Lesson 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 creation of packages.

## Objectives

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

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

## R

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

# 20.1 - Creating a Function

20.1 - Creating a Function

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

# 20.2 - Specifying Default Values for Arguments

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).

# 20.3 - Returning Values

20.3 - Returning Values

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

# 20.4 - Functions That Change Objects Are Risky

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.

# 20.5 - Debugging Errors and Checking Inputs

20.5 - Debugging Errors and Checking Inputs

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

# 20.6 - Sneaky Errors - NA Values

20.6 - Sneaky Errors - NA Values

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

# 20.7 - Creating a Package Part I

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.

# 20.8 - Creating a Package Part II

20.8 - Creating a Package Part II

We'll conclude this Chapter by finishing our demonstration on package creation.

 [1] Link ↥ Has Tooltip/Popover Toggleable Visibility