Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing NULL in purrr pmap

Tags:

r

purrr

pmap

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))
like image 877
MLEN Avatar asked Sep 15 '25 15:09

MLEN


1 Answers

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.

like image 171
MrFlick Avatar answered Sep 17 '25 04:09

MrFlick