0

Is it possible to use a nesting variable inside a function used in purrr::map? For example, in the following example I want each plot to have a title showing the number of cylinders

    library(tidyverse)
    plot_mtcars <- function(df, cyl){
                ggplot(aes(x = disp, y = mpg), data = df) + 
                        geom_point() +
                        ggtitle(paste("Cylinders =", cyl))
            }
    plots <- mtcars %>% 
                nest(-cyl) %>% 
                mutate(plot = map(data, ~plot_mtcars(., cyl)))

The code above does not work, as all plots return: Cylinders = 6 (instead of 6,4,8)

1 Answer 1

3

The issue here is that cyl is a vector, so it's setting a character vector in ggtitle, in which case only the first element is used; You need to loop through cyl and pass the corresponding element to the plot function:

plots <- mtcars %>% 
    nest(-cyl) %>% 
    # here use map2 to pass data and corresponding cyl to the plot function
    mutate(plot = map2(data, cyl, ~ plot_mtcars(.x, .y)))

Check the plot title:

plots$plot[[1]]$labels$title
# [1] "Cylinders = 6"

plots$plot[[2]]$labels$title
# [1] "Cylinders = 4"

plots$plot[[3]]$labels$title
# [1] "Cylinders = 8"
Sign up to request clarification or add additional context in comments.

2 Comments

What if nesting is done using 2 variables and I want to include both in the title. For example, plots <- mtcars %>% nest(-cyl, -am) %>% mutate(plot = map2...
Do you need to access both cyl and am in the plot function ? In which case you might use pmap something like pmap(list(data, cyl, am), ~ plot_mtcars(..1, ..2, ..3)) and your plot_mtcars function need to access three parameters as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.