How pipes work with purrr map () and "." (point)
When using both pipes and the map () function from purrr, I am confused about how data and variables are passed. For example, this code works as I expect:
library(tidyverse)
cars %>%
select_if(is.numeric) %>%
map(~hist(.))
However, when I try something like this with ggplot, it behaves in a strange way.
cars %>%
select_if(is.numeric) %>%
map(~ggplot(cars, aes(.)) + geom_histogram())
I guess it's because "." in this case a vector is passed to aes (), which expects a column name. Anyway, I would like to pass each numeric column to the ggplot function using pipe and map (). Thanks in advance!
+3
source to share
2 answers
cars %>%
select_if(is.numeric) %>%
map2(., names(.),
~{ggplot(data_frame(var = .x), aes(var)) +
geom_histogram() +
labs(x = .y) })
There are several additional steps.
- Use
map2
insteadmap
. The first argument is the dataframe you are passing to it, and the second argument is the vector ofnames
that dataframe, so it knows what to domap
. - Then you need to explicitly restrict your data, since it
ggplot
only works with data files and coercible objects. - It also gives you access to pronouns
.y
to name graphs.
+6
source to share