Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iteratively apply ggplot function within a map function

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.

like image 692
Joe Avatar asked Jun 11 '26 21:06

Joe


1 Answers

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())}
like image 98
acylam Avatar answered Jun 13 '26 10:06

acylam