In R, why is purrr's map2 ignoring my group_by argument when making plots?

Advertisements

I have many plots that I need to create broken out by students’ level. To do this, I want to use map2 from the purrr package. I want one plot for each level (so 4 plots altogether), but when I do group_by, the code creates one plot for each student (16 unique plots). *How do I get my code to make one plot for each grade rather than one for each student?

#My data
library(dplyr)
my_data <- tibble(level = c(rep(c("Kindergarten", "1st", "2nd", "3rd"), 4)),
                  id = c(1:16),
                  score = c(81:96))
#My attempt at making one plot per level--makes 16 plots instead of 4

library(purrr)
library(stringr)
library(ggplot2)

#Extract information
levels <- my_data %>% pull(level) %>% as.character
scores <- my_data %>% pull(score)

#Make plots
my_plots <- map2(
  .x = levels,
  .y = scores,
  .f = ~{
    my_data %>%
      group_by(level) %>% # I don't know why this is being ignored
      ggplot(aes(x = .x, y = .y)) +
      geom_point() +
      ggtitle(str_glue("Score by {.x}"))
  }
)

my_plots #has 16 plots (one for each data point) instead of 4 (one for each level with each respective student represented)

>Solution :

Please check the below code, i updated the code to use only map function with levels which we can use to filter the my_data

code

library(purrr)
levels <- my_data$level %>% unique()

#Make plots
my_plots <- map(
  .x = levels,
  .f = ~{
    my_data %>%
      filter(level == .x) %>% # I don't know why this is being ignored
      ggplot(aes(x = id, y = score)) +
      geom_point() +
      ggtitle(str_glue("Score by {.x}"))
  }
)

my_plots #has 16 plots (one for each data point) instead of 4 (one for each level with each respective student represented)

output

Leave a Reply Cancel reply