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:
Syntax
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()
a <- c(1, 2, 3)
b <- c(10, 20, 30)
result <- Map(function(x, y) x + y, a, b)
print(result)
Login to try C/C++/Java/PHP code in the editor
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
- Expecting a vector back from
Map(), when it returns a list; useunlist()to flatten. - Passing vectors of different lengths and being surprised by recycling.
- Confusing
Map()withmapfrom other languages, when the function comes first in R.