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

问题描述 投票:10回答:3

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

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))

我有以下函数显示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")
    }

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

get_charts1(ps_ind_07_bin)

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

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

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

listaplots <- map(quo(!!! syms(binarias)), get_charts1)

但这给了我以下错误:

"Error: Can't splice at top-level"

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

r ggplot2 tidyverse purrr tidyeval
3个回答
13
投票

我将首先创建一个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")
}

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

get_charts(ps_ind_06_bin)
get_charts(ps_ind_07_bin)
get_charts(ps_ind_08_bin)

这将需要for循环或apply / map函数。 map()在这里运行良好,因为我们想要返回ggplot2对象,并且使用for循环执行此操作需要更多的基础结构。一旦你记得你需要在这里使用符号,而不是原始字符串,这是直截了当的

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

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

## [[1]]

## 
## [[2]]

## 
## [[3]]


2
投票

而不是map,我想你想要invoke_map在这里。这似乎给你想要的东西

listaplots  <- invoke_map(get_charts1, rlang::syms(binarias))

map()似乎强制评估参数,而invoke_map则没有。


1
投票

enquo()更改为sym(),您的代码可以正常工作:

get_charts1 <- function(mygroup){
    quo_var <- sym(mygroup)  # <- HERE

    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")
}

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

binarias %>% map(get_charts1)
© www.soinside.com 2019 - 2024. All rights reserved.