map()returns the transformed input;
.ffor its side-effect and returns the original input.
map()returns a list or a data frame;
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, ...)
If a function, it is used as is.
If a formula, e.g.
~ .x + 2, it is converted to a
function with two arguments,
allows you to create very compact anonymous functions with up to
If character or integer vector, e.g.
is converted to an extractor function,
function(x) x[["y"]]. To
index deeply into a nested list, use multiple values;
is equivalent to
z[["x"]][["y"]]. You can also set
to set a default to use instead of
NULL for absent components.
NULLa variable with this name will be created giving either the name or the index of the data frame.
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
.fwill 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.
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++.
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)