【问题标题】:Passing NULL in purrr pmap在 purrr pmap 中传递 NULL
【发布时间】:2020-04-06 14:14:38
【问题描述】:

我有一个有时会返回 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))

【问题讨论】:

  • 谢谢。您能否发表您的评论作为答案,因为我发现解释和答案非常好?

标签: r purrr pmap


【解决方案1】:

您传递给pmap 的列表中的东西应该是“可迭代的”。 NULL 本身不能重复,因为大多数函数都设计为不将其视为对象。 length(NULL)==0 所以它看起来是空的。可以试试

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

相反。 NULL 的行为不像列表或向量,因此在使用它们时需要小心。在这里,通过将它放在一个列表中,可以迭代该列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2019-06-18
    • 1970-01-01
    相关资源
    最近更新 更多