Chapter 12 Functions
Learning Objectives
After completing this chapter, you will be able to:
- Define custom functions with arguments and default values
- Understand variable scoping and how R searches for variables
- Write anonymous functions for concise, one-off operations
- Use
...(dot-dot-dot) to pass additional arguments flexibly
In theory, you can already write very complicated codes, accomplishing a lot of data analysis tasks. In this chapter, you will learn a very powerful tool, functions.
At a glance – Chapter ROADMAP Section 12.1. Defining Functions: Learn to create custom, reusable blocks of code with arguments and return values.
Section 12.2 & Section 12.3. Advanced Concepts: Master anonymous functions, nested functions, and understand variable scoping rules in R.
Section 12.4. Functional Programming: Use theapplyfamily andpurrrfor cleaner, more efficient iteration over lists and data frames.
Section 12.5. Robustness: ImplementtryCatch()and other tools to handle errors and warnings gracefully.