Working With Vectorized Functions

In the Working with Control Structures lession, you learned how to repeat operations on multiple elements of a data frame or list using for loops. 

Loops are a common feature of programming languages — the process of iterating over an object that contains multiple elements (such as a list), repeating operations on each element, and saving the result is a common programming task. Understanding how for loops work is important as you build your programming foundation.

When working with R, though, you won't write for loops as often as you would if you were using other programming languages. In R, many built-in functions already contain for loops. This makes it possible to call a function instead of directly using a for loop. Remember from earlier courses that functions take an input, perform an operation, and return an output.

In this lesson, you will delve deeper into some of R's vectorized functions. You’ll learn why they will help you write fast and efficient code, and why and when you should use them. We'll also show you how to use the pipe operator (`%>%`) to write efficient code by chaining functions together. 

In addition, you will learn more about the `dplyr` package, including how to use functions such as `group_by()` and `summarize()` that are useful for working on split-apply-combine problems.


  • Use vectorized functions for if-else statements.
  • Solve split-apply-combine-problems.
  • Learn best practices for chaining multiple functions together.

Lesson Outline

1. R Functions as Alternatives to Loops
2. How Does Vectorization Make Code Faster?
3. A Vectorized Function for If-Else Statements
4. Multiple Cases: Nesting Functions to Chain If-Else Statements
5. Functions for Solving "Split-Apply-Combine" Problems
6. Grouping and Summarizing Data Frames
7. Summarizing a Data Frame by Multiple Variables
8. Chaining Functions Together Using the Pipe Operator
9. Next Steps
10. Takeaways

Take a Look Inside