rguides

Map

Map() is a base R function that applies a function to multiple arguments in parallel. It is equivalent to mapply() with simplification disabled, meaning it always returns a list regardless of the result shape.

Relationship to mapply

Map() is a thin wrapper around mapply:

Map(f, x, y)
# identical to
mapply(f, x, y, SIMPLIFY = FALSE)

The difference is that Map() never attempts to simplify the result. mapply() tries to collapse the list into a matrix or vector when all results are scalar — Map() skips that step.

Basic Usage

# Apply a function to two vectors element-wise
Map(\(x, y) x + y, 1:3, 10:12)
# [[1]]
# [1] 11
# [[2]]
# [1] 13
# [[3]]
# [1] 15

# Compare to mapply (which simplifies)
mapply(\(x, y) x + y, 1:3, 10:12)
# [1] 11 13 15

Parameter Details

ParameterTypeDefaultDescription
FUNfunctionRequiredFunction to apply
...vectors/listsRequiredArguments to iterate over
MoreArgslistNULLAdditional fixed arguments to pass to FUN
USE.nameslogicalTRUEIf TRUE and any argument has names, the result inherits those names
SIMPLIFYlogicalFALSEAlways FALSE for Map (enforced)

Working With Names

# Names are preserved when USE.names = TRUE (default)
Map(\(name, val) paste0(name, ": ", val),
    c(a = "apple", b = "banana"),
    1:2)
# $a
# [1] "apple: 1"
# $b
# [1] "banana: 2"

Passing Extra Arguments

Use MoreArgs to pass additional fixed arguments:

f <- function(x, y, z) x + y * z

Map(f, 1:3, 10:12, MoreArgs = list(z = 2))
# [[1]]
# [1] 21
# [[2]]
# [1] 25
# [[3]]
# [1] 29

Multiple List Inputs

# Apply function across multiple lists
x <- list(a = 1, b = 2)
y <- list(a = 10, b = 20)
z <- list(a = 100, b = 200)

Map(\(a, b, c) a + b + c, x, y, z)
# $a
# [1] 111
# $b
# [1] 222

When to Use Map vs mapply

Use Map() when you want predictable list output. Use mapply() when you want the result simplified to a vector or matrix — but be aware that simplification can fail in unexpected ways if the return types vary.

# Safe: always list, no surprises
result <- Map(function(x) if (x > 1) "big" else "small", 1:3)
str(result)
# List of 3

# mapply simplifies when possible
result <- mapply(function(x) if (x > 1) "big" else "small", 1:3)
str(result)
#  chr [1:3] "small" "big" "big"

See Also