0

I'm trying to use a ggplot function that I can use in a pipe with pmap, feeding a tibble of variables. These variables include the data frame, filtering options and plotting variables.

The function works but in the context of pmap it doesn't with an error: Error in UseMethod("filter") : no applicable method for 'filter' applied to an object of class "character"

library(tidyverse)
library(palmerpenguins)

make_plot <- function(dat, species) {
  dat %>%
    filter(.data$species == .env$species) %>%
    ggplot() +
    aes(bill_length_mm, body_mass_g, color=sex) +
    geom_point() +
    ggtitle(glue("Species: {species}")) +
    xlab("bill length (mm)") +
    ylab("body mass (g)") +
    theme(plot.title.position = "plot")
}

species <- c("Adelie", "Chinstrap", "Gentoo")
penguins_vars <- tibble(dat = rep("penguins", 3), species = species)

plots <- pmap(penguins_vars, make_plot)

#function still works:
make_plot(penguins, "Adelie")

1 Answers1

0

pmap essentially iterates through the rows of the tibble (penguins_vars) so when it's called, make_plot is passed the string "penguins" not the data set (like it is in the working call). I think you want something like this:

plots <- map(species, make_plot, dat = penguins) 
Marcus
  • 3,478
  • 1
  • 7
  • 16
  • Thanks. But that doesn’t let me iterate through different data sources. How to I ‘unstrung’ the data variable within the function? – Juan Manuel Schvartzman Nov 19 '22 at 19:34
  • What different data sources? penguins is the only data source. If you want to iterate through different data sets, you should be passing the entire data set into your function. To create a suitable argument for `map` or `pmap` to iterate over, look into nested data: https://tidyr.tidyverse.org/articles/nest.html – Marcus Nov 21 '22 at 15:51