0

My data-frame has multiple categorical columns, I want to compare each column the with fixed column and generate the bar graph with facet_grid(). For that I want to write a function.

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

Here Target column is fixed for group_by() and facet_grid() functions. In the similar way I want to compare with multiple columns.

For that I wrote a function

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

The above function up to group_by() is working before getting the error.

Tung
  • 26,371
  • 7
  • 91
  • 115
dondapati
  • 829
  • 6
  • 18
  • How did you call your function? What was the error? – Tung Jun 29 '18 at 18:36
  • @ Tung sorry for late replay. i passing the paramete `cateby_label_graph('type')` and Error is `Don't know how to automatically pick scale for object of type list. Defaulting to continuous. Error in unique.default(x, nmax = nmax) : unique() applies only to vectors` – dondapati Jul 02 '18 at 05:06

1 Answers1

0

You want sym (not syms) and need to unquote x using !! in your ggplot call

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

Created on 2018-07-02 by the reprex package (v0.2.0.9000).

Tung
  • 26,371
  • 7
  • 91
  • 115