如何使用purrr循环整理eval函数?

Ram*_*tes 10 r ggplot2 purrr tidyverse tidyeval

我有以下数据集(示例):

train <- data.frame(ps_ind_06_bin = c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE),
                        ps_ind_07_bin = c(FALSE, TRUE, TRUE, FALSE, TRUE, TRUE),
                        ps_ind_08_bin = c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE),
                        ps_ind_09_log = c(1, 3, 4, 2, 3, 2))
Run Code Online (Sandbox Code Playgroud)

我有以下函数显示group_by()操作的ggplot :

get_charts1 <- function(mygroup){
  quo_var <- enquo(mygroup)
  train %>% 
    group_by(!!quo_var) %>% 
    count() %>%
    ungroup() %>%
  ggplot(aes_q(x = quo_var, y = quote(n), fill = quo_var)) + 
    geom_col() +
    theme(legend.position = "none")
    }
Run Code Online (Sandbox Code Playgroud)

我手动输入列名称时工作正常,例如:

get_charts1(ps_ind_07_bin)
Run Code Online (Sandbox Code Playgroud)

但是,我想在几个列上使用该函数,我将它放在一个向量上:

binarias <- train %>% 
             select(ends_with("bin")) %>% 
             colnames()
Run Code Online (Sandbox Code Playgroud)

使用地图并提出一些建议,我试图使用:

listaplots <- map(quo(!!! syms(binarias)), get_charts1)
Run Code Online (Sandbox Code Playgroud)

但这给了我以下错误:

"Error: Can't splice at top-level"
Run Code Online (Sandbox Code Playgroud)

有谁知道我需要做些什么才能让它发挥作用?

had*_*ley 14

我将首先创建一个 reprex(你非常接近,但忘记加载所需的包),并使用styler重新设置为一致的格式:

library(tidyverse)
library(rlang)

train <- data.frame(
  ps_ind_06_bin = c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE),
  ps_ind_07_bin = c(FALSE, TRUE, TRUE, FALSE, TRUE, TRUE),
  ps_ind_08_bin = c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE),
  ps_ind_09_log = c(1, 3, 4, 2, 3, 2)
)

get_charts <- function(mygroup) {
  quo_var <- enquo(mygroup)
  train %>%
    group_by(!! quo_var) %>%
    count() %>%
    ungroup() %>%
    ggplot(aes_q(x = quo_var, y = quote(n), fill = quo_var)) +
    geom_col() +
    theme(legend.position = "none")
}
Run Code Online (Sandbox Code Playgroud)

您希望自动生成如下代码:

get_charts(ps_ind_06_bin)
get_charts(ps_ind_07_bin)
get_charts(ps_ind_08_bin)
Run Code Online (Sandbox Code Playgroud)

这将需要for循环或apply/map函数.一个map() 运作良好,因为在这里我们要返回的GGPLOT2对象,这样做有一个for循环需要更多的基础设施.一旦你记得你需要在这里使用符号,而不是原始字符串,这是直截了当的

vars <- train %>% select(ends_with("bin")) %>% colnames()

vars %>%
  syms() %>%
  map(function(var) get_charts(!!var))

## [[1]]
Run Code Online (Sandbox Code Playgroud)

## 
## [[2]]
Run Code Online (Sandbox Code Playgroud)

## 
## [[3]]
Run Code Online (Sandbox Code Playgroud)


MrF*_*ick 2

而不是map,我认为你想要invoke_map这里。这似乎给了你想要的

listaplots  <- invoke_map(get_charts1, rlang::syms(binarias))
Run Code Online (Sandbox Code Playgroud)

map()似乎强制评估参数,但事实invoke_map并非如此。