使用 dplyr 和 enquo 我的代码有效但当我传递给 purrr::map

With dplyr and enquo my code works but not when I pass to purrr::map

我想为称为日期的向量中的每一列创建一个图。我的数据框只包含这些列,我想对其进行分组,计算出现次数,然后绘制它。

下面的代码有效,但 map 除外,我想用它来遍历以前未知数量的列。我想我使用 map 是正确的,我以前用它取得过成功。我是使用 quosures 的新手,但考虑到我的函数调用有效,我不确定哪里出了问题。我查看了其他几篇似乎以这种方式设置的帖子。

df <- data.frame(
  date1 = c("2018-01-01","2018-01-01","2018-01-01","2018-01-02","2018-01-02","2018-01-02"),
  date2 = c("2018-01-01","2018-01-01","2018-01-01","2018-01-02","2018-01-02","2018-01-02"),
  stringsAsFactors = FALSE
)
dates<-names(df)

library(tidyverse)

dates.count<-function(.x){
  group_by<-enquo(.x)
  df %>% group_by(!!group_by) %>% summarise(count=n()) %>% ungroup() %>% ggplot() + geom_point(aes(y=count,x=!!group_by))
}
dates.count(date1)
map(dates,~dates.count(.x))

我收到此错误:grouped_df_impl(data, unname(vars), drop) 中的错误:列 .x 未知

当您将变量名称传递给 map() 时,您使用的是字符串,这表明您需要 ensym() 而不是 enquo()

所以你的函数看起来像

dates.count <- function(.x){
    group_by = ensym(.x)
    df %>% 
        group_by(!!group_by) %>% 
        summarise(count=n()) %>% 
        ungroup() %>% 
        ggplot() + 
        geom_point(aes(y=count,x=!!group_by))
}

并且您将使用变量名称作为参数的字符串。

dates.count("date2")

请注意,tidyeval 并不总是与 map() 的公式界面配合得很好(我想我没有记错)。您始终可以执行匿名函数,但是在您想要将列名映射到具有单个参数的函数的情况下,您可以执行

map(dates, dates.count)

使用 map() 中的公式界面我需要一个额外的 !!:

map(dates, ~dates.count(!!.x))