3

I have a function that sometimes returns NULL and I try to pass it later on using pmap. When I call the same function directly it works fine, but not with pmap. Is this expected, if so, why? Any workaround?

library(tidyverse)

plot_fun <- function(data, color_by){

  plot <- ggplot(data, aes_string(x = 'Sepal.Length', 
                                  y = 'Sepal.Width',
                                  color = color_by)) +
    geom_point()

  return(plot)


}

# works fine:

plot_fun(iris, 'Species')
plot_fun(iris, NULL)
pmap(list(list(iris), 'Species'), plot_fun)

# does not work:

pmap(list(list(iris), NULL), plot_fun)
pmap(list(list(iris), NULL), ~plot_fun(..1, ..2))
MLEN
  • 2,162
  • 2
  • 20
  • 36
  • Thanks. Could you post your comment as an answer as I found the explanation and answer very good? – MLEN Apr 06 '20 at 14:46

1 Answers1

2

The things in the list you pass to pmap should be "iterable". A NULL on it's own can't beiterated becuase most functions are designed not to see it as an object. length(NULL)==0 so it looks empty. Maybe try

pmap(list(list(iris), list(NULL)), plot_fun) 

instead. NULLs don't behave like lists or vectors so you need to be careful when using them. Here, by putting it in a list, that list can be iterated over.

MrFlick
  • 195,160
  • 17
  • 277
  • 295