在自定义函数中将列名传递给group_by和ggplot2

时间:2018-06-29 11:20:42

标签: r ggplot2 dplyr tidyeval

我的数据框具有多个分类列,我想将每个列与固定列进行比较,并使用facet_grid()生成条形图。为此,我想编写一个函数。

library(rlang)
library(tidyverse)

qw <- structure(list(weekday = structure(c(2L, 6L, 7L, 5L, 1L, 3L, 
  4L, 2L, 6L, 7L, 5L, 1L, 3L, 4L, 2L, 6L, 7L, 5L, 1L, 3L, 4L, 2L, 
  6L, 7L, 5L, 1L, 3L, 4L, 2L, 6L, 7L, 5L, 1L, 3L, 4L), .Label = c("Friday", 
  "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"
  ), class = "factor"), Target = c(0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 
  0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 
  1, 0, 0, 1), type = structure(c(3L, 3L, 2L, 3L, 1L, 3L, 1L, 3L, 
  1L, 1L, 3L, 2L, 1L, 3L, 3L, 1L, 3L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 
  1L, 3L, 2L, 1L, 2L, 1L, 2L, 1L, 3L, 2L, 3L), .Label = c("Advertising", 
  "Agriculture", "Bank"), class = "factor")), .Names = c("weekday", 
  "Target", "type"), row.names = c(NA, -35L), class = "data.frame")

qw %>%
  group_by(type, Target) %>%
  summarise(Freq = n()) %>%
  ggplot(data = ., aes(x = reorder(type, -Freq), y = Freq, fill = type)) +
  geom_bar(stat = 'identity') +
  labs(y = "", x = "") +
  facet_grid(Target ~ ., scales = "free") + 
  theme(legend.position = 'none')

此处目标列固定用于group_by()facet_grid()函数。 我想以类似的方式与多列进行比较。

为此,我编写了一个函数

cateby_label_graph <- function(x){
  x <- syms(x)
  qw %>% 
    group_by(!!!x, Target) %>%
    summarise(Freq = n()) %>% 
    ggplot(data = . , aes(x = reorder(x, -Freq), y = Freq, fill = x)) +
    geom_bar(stat = 'identity') + 
    labs(y = "", x = "") +
    facet_grid(Target~., scales="free") + 
    theme(legend.position = 'none')
}

在收到错误之前,直到group_by()的上述函数都可以正常工作。

1 个答案:

答案 0 :(得分:0)

您需要sym(而不是syms),并且需要在x通话中使用!!取消对ggplot的报价

# Need ggplot2 3.0.0 to use tidy evaluation in ggplot2
# install.packages("ggplot2", dependencies = TRUE)

library(rlang)
library(tidyverse)

cateby_label_graph2 <- function(df, x) {

  x <- sym(x)

  df %>% 
    group_by(!! x, Target) %>%
    summarise(Freq = n()) %>% 
    ggplot(data = ., aes(x = reorder(!! x, -Freq), y = Freq, fill = !! x)) +
    geom_col() + 
    labs(y = "", x = "") +
    facet_grid(Target ~ ., scales = "free") + 
    theme(legend.position = 'none')
}

cateby_label_graph2(qw, 'type')

reprex package(v0.2.0.9000)于2018-07-02创建。

相关问题