When using both pipes and the map() function from purrr, I am confused about how data and variables are passed along. For instance, this code works as I expect:
library(tidyverse)
cars %>%
select_if(is.numeric) %>%
map(~hist(.))
Yet, when I try something similar using ggplot, it behaves in a strange way.
cars %>%
select_if(is.numeric) %>%
map(~ggplot(cars, aes(.)) + geom_histogram())
I'm guessing this is because the "." in this case is passing a vector to aes(), which is expecting a column name. Either way, I wish I could pass each numeric column to a ggplot function using pipes and map(). Thanks in advance!
You aren't supposed to pass raw data to an aesthetic mapping. Instead you should dynamically build the data.frame. For example
There's a few extra steps.
map2
instead ofmap
. The first argument is the dataframe you're passing it, and the second argument is a vector of thenames
of that dataframe, so it knows what tomap
over. (Alternately,imap(x, ...)
is a synonym formap2(x, names(x), ...)
. It's an "index-map", hence "imap".).ggplot
only works on dataframes and coercible objects..y
pronoun to name the plots.