如何将裸元素列表传递给接受裸元素到 purrr 映射的 tidyeval plot 函数
How to pass a list of bare elements to a tidyeval plot function that accepts bare elements to purrr map
给定以下函数类型:
library(tidyverse)
make_plot <- function(var) {
quo_var <- enquo(var)
ggplot(mtcars, aes(x = !!quo_var, y = mpg)) +
geom_point()
}
我想在 data.frame 的各个列上这样调用它:
make_plot(hp)
make_plot(am)
...
但为了让代码保持干爽,我想使用 purrr::map
或 purrr::walk
,但以下内容不起作用:
list(hp, am) %>%
map(make_plot)
我也试过list("hp", "am") %>% map(make_plot(sym(.))
,但还是不行。使用字符串或变量列表的正确方法是什么?
我们可以用 quote
换行以避免提前求值
library(tidyverse)
library(ggplot2)
list(quote(hp), quote(am)) %>%
map(make_plot)
或者另一种选择是将其作为 quosure
(quos
)
的列表传递
quos(hp, am) %>%
map(make_plot)
-最后剧情
要使 ~ .x
正常工作,请使用 !!
进行评估
quos(hp, am) %>%
walk(~ print(make_plot(!! .x)))
给定以下函数类型:
library(tidyverse)
make_plot <- function(var) {
quo_var <- enquo(var)
ggplot(mtcars, aes(x = !!quo_var, y = mpg)) +
geom_point()
}
我想在 data.frame 的各个列上这样调用它:
make_plot(hp)
make_plot(am)
...
但为了让代码保持干爽,我想使用 purrr::map
或 purrr::walk
,但以下内容不起作用:
list(hp, am) %>%
map(make_plot)
我也试过list("hp", "am") %>% map(make_plot(sym(.))
,但还是不行。使用字符串或变量列表的正确方法是什么?
我们可以用 quote
换行以避免提前求值
library(tidyverse)
library(ggplot2)
list(quote(hp), quote(am)) %>%
map(make_plot)
或者另一种选择是将其作为 quosure
(quos
)
quos(hp, am) %>%
map(make_plot)
-最后剧情
要使 ~ .x
正常工作,请使用 !!
quos(hp, am) %>%
walk(~ print(make_plot(!! .x)))