在 purrr 的 pmap 函数中传递 NULL

3

我有一个函数,有时会返回NULL,并且我尝试稍后使用pmap传递它。当我直接调用相同的函数时,它能够正常工作,但是在使用pmap时却不行。这是预期的吗?如果是,为什么?有没有解决方法?

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
1个回答

2
你传递给 pmap 的列表中的元素应该是“可迭代”的。一个单独的 NULL 无法被迭代,因为大多数函数都不会将其视为对象。length(NULL)==0,所以它看起来是空的。也许尝试使用其他可迭代的对象。
pmap(list(list(iris), list(NULL)), plot_fun) 

相反,NULL不像列表或向量那样表现,因此在使用时需要小心。在这里,通过将其放入列表中,该列表可以被迭代。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接