我有一个函数,有时会返回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))发布于 2020-04-07 03:17:21
你传递给pmap的列表中的内容应该是“可迭代的”。NULL本身不能被迭代,因为大多数函数都被设计成不会将其视为对象。length(NULL)==0,因此它看起来是空的。也许可以试一下
pmap(list(list(iris), list(NULL)), plot_fun) 而不是。NULL的行为与列表或向量不同,因此在使用它们时需要小心。在这里,通过将其放入列表中,可以迭代该列表。
https://stackoverflow.com/questions/61061847
复制相似问题