map {purrr} | R Documentation |
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); map_df()
returns
a data frame by row-binding the individual elements.
map(.x, .f, ...) map_lgl(.x, .f, ...) map_chr(.x, .f, ...) map_int(.x, .f, ...) map_dbl(.x, .f, ...) map_df(.x, .f, ..., .id = NULL) walk(.x, .f, ...)
.x |
A list or atomic vector. |
.f |
A function, formula, or atomic vector. If a function, it is used as is. If a formula, e.g. If character or integer vector, e.g. |
... |
Additional arguments passed on to |
.id |
If not |
Note that map()
understands data frames, including grouped
data frames. It can be much faster than
mutate_each()
when your data frame has many
columns. However, map()
will be slower for the more common case of many
groups with functions that dplyr knows how to translate to C++.
map()
always returns a list.
map_lgl()
returns a logical vector, map_int()
an integer
vector, map_dbl()
, a double vector, map_chr()
, a character
vector. The output of .f
will be automatically typed upwards,
e.g. logical -> integer -> double -> character.
walk()
(invisibly) the input .x
. It's called primarily for
its side effects, but this makes it easier to combine in a pipe.
map2()
and pmap()
to map over multiple
inputs simulatenously
1:10 %>% map(rnorm, n = 10) %>% map_dbl(mean) # 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) # If each element of the output is a data frame, use # map_df to row-bind them together: mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .x)) %>% map_df(~ as.data.frame(t(as.matrix(coef(.))))) # (if you also want to preserve the variable names see # the broom package)