Description
The map functions transform their input by applying a function toeach element of a list or atomic vector and returning an object ofthe same length as the input.
map()
always returns a list. See themodify()
family forversions that return an object of the same type as the input.map_lgl()
,map_int()
,map_dbl()
andmap_chr()
return anatomic vector of the indicated type (or die trying). For these functions,.f
must return a length-1 vector of the appropriate type.map_vec()
simplifies to the common type of the output. It works withmost types of simple vectors like Date, POSIXct, factors, etc.walk()
calls.f
for its side-effect and returnsthe input.x
.
Usage
map(.x, .f, ..., .progress = FALSE)map_lgl(.x, .f, ..., .progress = FALSE)
map_int(.x, .f, ..., .progress = FALSE)
map_dbl(.x, .f, ..., .progress = FALSE)
map_chr(.x, .f, ..., .progress = FALSE)
See Alsomap function - RDocumentationExploring apply, sapply, lapply, and map Functions in Rmap: Apply a function to each element of a vector in purrr: Functional Programming ToolsApply a function to each element of a vector — mapmap_vec(.x, .f, ..., .ptype = NULL, .progress = FALSE)
walk(.x, .f, ..., .progress = FALSE)
Value
The output length is determined by the length of the input.The output names are determined by the input names.The output type is determined by the suffix:
No suffix: a list;
.f()
can return anything._lgl()
,_int()
,_dbl()
,_chr()
return a logical, integer, double,or character vector respectively;.f()
must return a compatible atomicvector of length 1._vec()
return an atomic or S3 vector, the same type that.f
returns..f
can return pretty much any type of vector, as long as its length 1.walk()
returns the input.x
(invisibly). This makes it easy touse in a pipe. The return value of.f()
is ignored.
Any errors thrown by .f
will be wrapped in an error with classpurrr_error_indexed.
Arguments
A list or atomic vector. A function, specified in one of the following ways: A named function, e.g. An anonymous function, e.g. A formula, e.g. A string, integer, or list, e.g. Additional arguments passed on to the mapped function. We now generally recommend against using This makes it easier to understand which arguments belong to whichfunction and will tend to yield better error messages. Whether to show a progress bar. Use If mean
.\(x) x + 1
or function(x) x + 1
.~ .x + 1
. You must use .x
to refer to the firstargument. Only recommended if you require backward compatibility witholder versions of R."idx"
, 1
, or list("idx", 1)
whichare shorthand for \(x) pluck(x, "idx")
, \(x) pluck(x, 1)
, and\(x) pluck(x, "idx", 1)
respectively. Optionally supply .default
toset a default value if the indexed element is NULL
or does not exist....
to pass additional(constant) arguments to .f
. Instead use a shorthand anonymous function:# Instead ofx |> map(f, 1, 2, collapse = ",")# do:x |> map(\(x) f(x, 1, 2, collapse = ","))
TRUE
to turn ona basic progress bar, use a string to give it a name, or seeprogress_bars for more details.NULL
, the default, the output type is the common typeof the elements of the result. Otherwise, supply a "prototype" givingthe desired type of output.
See Also
map_if()
for applying a function to only those elementsof .x
that meet a specified condition.
Other map variants: imap()
,lmap()
,map2()
,map_depth()
,map_if()
,modify()
,pmap()
Examples
# Compute normal distributions from an atomic vector1:10 |> map(rnorm, n = 10)# You can also use an anonymous function1:10 |> map(\(x) rnorm(10, x))# Simplify output to a vector instead of a list by computing the mean of the distributions1:10 |> map(rnorm, n = 10) |> # output a list map_dbl(mean) # output an atomic vector# Using set_names() with character vectors is handy to keep track# of the original inputs:set_names(c("foo", "bar")) |> map_chr(paste0, ":suffix")# Working with listsfavorite_desserts <- list(Sophia = "banana bread", Eliott = "pancakes", Karina = "chocolate cake")favorite_desserts |> map_chr(\(food) paste(food, "rocks!"))# Extract by name or position# .default specifies value for elements that are missing or NULLl1 <- list(list(a = 1L), list(a = NULL, b = 2L), list(b = 3L))l1 |> map("a", .default = "???")l1 |> map_int("b", .default = NA)l1 |> map_int(2, .default = NA)# Supply multiple values to index deeply into a listl2 <- list( list(num = 1:3, letters[1:3]), list(num = 101:103, letters[4:6]), list())l2 |> map(c(2, 2))# Use a list to build an extractor that mixes numeric indices and names,# and .default to provide a default value if the element does not existl2 |> map(list("num", 3))l2 |> map_int(list("num", 3), .default = NA)# Working with data frames# Use map_lgl(), map_dbl(), etc to return a vector instead of a list:mtcars |> map_dbl(sum)# A more realistic example: split a data frame into pieces, fit a# model to each piece, summarise and extract R^2mtcars |> split(mtcars$cyl) |> map(\(df) lm(mpg ~ wt, data = df)) |> map(summary) |> map_dbl("r.squared")
Run the code above in your browser using DataLab