我试图通过 pmap() 变得更好,但我遇到了一些错误。在这个例子中,我有一个简单的图形函数,我想迭代它。我对 pmap() 的理解是我可以设置和定义无限数量的参数。但是,我很困惑为什么它说 .z 没有定义,而我已经明确定义了它。
除非必要,否则我对更改参数定义的任何方式不感兴趣——我只是想了解并解决为什么我不能拥有第三个参数,即使 .x 和 .y 工作正常(即使我切换定义为 .x、.y 和 .z 的内容)。
library(purrr)
library(ggplot2)
library(dplyr)
#Plot function
make_chart <- function(data, x, y, xtitle){
require(stringr)
ggplot(data, aes(x = as.factor({{x}}), y = {{y}})) +
geom_col() +
ggtitle(paste0("Number of ", str_to_title({{xtitle}}), " by MPG")) +
xlab({{xtitle}})
}
#Define x variables
x_variables <- c("cyl", "vs", "am", "gear", "carb")
#pmap it--why is .z not found and how do I get it to be?
pmap(list(.x = mtcars %>% dplyr::select(matches(x_variables)),
.y = x_variables,
.z = mtcars %>% dplyr::select(mpg)),
~mtcars %>%
make_chart(x = .x, xtitle = .y, y = .z))
来自
?pmap
pmap(.l, .f, ..., .progress = FALSE)
=> 向量列表。 .l 的长度决定了调用 .f 时使用的参数数量。如果未命名,参数将按位置提供,如果命名,则按名称提供。.l
要么使用匿名函数按列表中的名称(首选方式)为
make_chart
提供参数,要么使用公式语法按位置提供参数,
# using anonymous function to supply argument by name
pmap(.l = list(x = mtcars %>% dplyr::select(matches(x_variables)),
y = x_variables,
z = mtcars %>% dplyr::select(mpg)),
.f = \(x, y, z) mtcars %>% make_chart(x = x, xtitle = y, y = z))
或者,
# supplying arguments by position
pmap(.l = list(mtcars %>% dplyr::select(matches(x_variables)),
x_variables,
mtcars %>% dplyr::select(mpg)),
.f = ~ mtcars %>% make_chart(x = ..1, xtitle = ..2, y = ..3))