← Back to R Course | Chapter 11: Apply Family | Lesson 5 of 6

Map()

Map walks through two or more lists side by side and applies a function to each matching pair, like pairing each child with their own name tag. It gives back a list of results.

In this page:

  1. Map()
Syntax
r
Map(FUN, x, y)

Map()

Map(FUN, x, y, ...) applies a function to corresponding elements of two or more vectors/lists in parallel, similar to zip-and-apply in other languages.

Unlike sapply(), which iterates over a single input, Map() is built for combining multiple inputs element-wise. It always returns a list, like lapply().

Note: Map() is how you apply a function across two (or more) vectors in parallel -- sapply()/lapply() only handle a single input vector.

Example: Map()

markup
a <- c(1, 2, 3)
b <- c(10, 20, 30)

result <- Map(function(x, y) x + y, a, b)
print(result)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a vector back from Map(), when it returns a list; use unlist() to flatten.
  2. Passing vectors of different lengths and being surprised by recycling.
  3. Confusing Map() with map from other languages, when the function comes first in R.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.