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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With