using purrr::map instead of a for loop

Hello dear community

I need some help, if possible.

to show my question, i created the following code:

library(tidyverse)

# create a tibble with dummy values
df <- tibble(category = rep(seq(1,5), 4),
             val = rnorm(20, 1, 5))

# create a function that plots the dummy values per category
gplot <- function(tib, cat){
    tib %>% filter(category == cat) %>% 
        ggplot(aes(category, val))+
        geom_jitter()
}


l <- list()

#iterate along categories and produce a plot per category
for (i in seq(min(df$category), max(df$category))){ 
    l[[i]] <- df %>% filter(category == i) %>% 
        gplot(tib = df, cat = i) 
}

basically it created 2 column tibble, with category and value. I also created a function that creates a plot. I would like to itertate as shown above to produce a plot per category.

​

Is this possible using purrr::map?

​

thanks for your help

Posted Aug 16, 2021, 3:45 PM UTC

69
Loading comments…