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)                    })

      

enter image description here

enter image description here



There are several additional steps.

  • Use map2

    instead map

    . The first argument is the dataframe you are passing to it, and the second argument is the vector of names

    that dataframe, so it knows what to do map

    .
  • 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


You shouldn't be passing raw data into aesthetic mapping. Instead, you should dynamically build the data.frame. for example



cars %>% 
  select_if(is.numeric) %>% 
  map(~ggplot(data_frame(x=.), aes(x)) + geom_histogram())

      

+8


source







All Articles