3
votes

I would like to generate a series of histograms for all variables in a dataset, but I am clearly not preparing the data correctly for use in the map function.

library(tidyverse)

mtcars %>% 
  select(wt, disp, hp) %>% 
  map(., function(x)
    ggplot(aes(x = x)) + geom_histogram()
)

I can accomplish this task with a for loop (h/t but am trying to do the same thing within the tidyverse.

foo <- function(df) {
  nm <- names(df)
  for (i in seq_along(nm)) {
print(
  ggplot(df, aes_string(x = nm[i])) + 
  geom_histogram()) 
  }
}

mtcars %>% 
  select(wt, disp, hp) %>% 
  foo(.)

Any help is greatly appreciated.

2
Do you need to create distinct plots for each, or would a faceting solution be ok? - joran

2 Answers

5
votes

Something like this would also work:

library(purrr)
library(dplyr)
mtcars %>% 
  select(wt, disp, hp) %>% 
  names() %>%
  map(~ggplot(mtcars, aes_string(x = .)) + geom_histogram())

or:

mtcars %>% 
  select(wt, disp, hp) %>% 
  {map2(list(.), names(.), ~ ggplot(.x, aes_string(x = .y)) + geom_histogram())}
2
votes

To use purrr::map, you could melt your data frame, and then split it based on the variable name into a list of data frames

library(reshape2)
library(dplyr)
library(ggplot2)
library(purrr)

melt(mtcars) %>%
  split(.$variable) %>%
  map(., ~ggplot(.x, aes(x=value)) + 
            geom_histogram())

You can also use ggplot2::facet_wrap to plot them all at once

library(reshape2)
library(dplyr)
library(ggplot2)

melt(mtcars) %>% 
  ggplot(., aes(x=value, label=variable)) + 
  geom_histogram() + 
  facet_wrap(~variable, nrow=ncol(mtcars))