Learn R Programming

purrr (version 0.1.0)

map: Apply a function to each element of a list.

Description

map() returns the transformed input; walk() calls .f for its side-effect and returns the original input. map() returns a list or a data frame; map_lgl(), map_int(), map_dbl() and map_chr() return vectors of the corresponding type (or die trying).

Usage

map(.x, .f, ...)

map_lgl(.x, .p, ...)

map_chr(.x, .f, ...)

map_int(.x, .f, ...)

map_dbl(.x, .f, ...)

walk(.x, .f, ...)

Arguments

.x
A list or vector.
.f
A function, formula or string.

If a function, it is used as is.

If a formula, e.g. ~ .x + 2, it is converted to a function with a three arguments, .x or ., .y, .z. This allows you

...
Additional arguments passed on to .f.
.p
A predicate: either a function, in any of the ways possible for .f, or a logical vector the same length as .x.

Value

  • map() a list if .x is a list or a data frame if .x is a data frame.

    map_lgl() returns a logical vector, map_int() an integer vector, map_dbl(), a numeric vector, map_chr(), a character vector.

    walk() (invisibly) the input .x. It's called primarily for its side effects, but this makes it easier to combine in a pipe.

See Also

map2() and map3() to map over multiple inputs simulatenously

Examples

Run this code
1:10 %>%
  map(rnorm, n = 10) %>%
  map(mean, .type = numeric(1))

# Or use an anonymous function
1:10 %>%
  map(function(x) rnorm(10, x))

# Or a formula
1:10 %>%
  map(~ rnorm(10, .x))

# A more realistic example: split a data frame into pieces, fit a
# model to each piece, summarise and extract R^2
mtcars %>%
  split(.$cyl) %>%
  map(~ lm(mpg ~ wt, data = .x)) %>%
  map(summary) %>%
  map_dbl("r.squared")

# Use map_lgl(), map_dbl(), etc to reduce to a vector.
# * list
mtcars %>% map(sum)
# * vector
mtcars %>% map_dbl(sum)

Run the code above in your browser using DataLab