kyg
kyg

Reputation: 105

Creating an R function containing dplyr and ggplot

I am trying to build an R function that contains dplyr and ggplot but keep getting errors. I've looked at other solutions but cannot seem to make it fit to mine.

I've replicated my problem using the iris dataset.

Without a function and looks like this:

cat_dat <- iris %>%
     group_by(Species) %>%
     summarise(mean=mean(Sepal.Length)) 

bar_num <- ggplot(cat_dat, aes(x=Species, y=mean)) +
     geom_bar(stat='identity')

bar_num

enter image description here

But when I try to enclose the same code in a function like this, I get different chart:

bar_viz <- function(data, grp_var, var) {
     
     enq_grp_var <- enquo(grp_var)
     
     cat_dat <- iris %>%
          group_by(!!rlang::sym(grp_var)) %>%
          summarise(mean=mean(!!rlang::sym(var))) 

     bar_num <- ggplot(cat_dat, aes(x=grp_var, y=mean)) +
          geom_bar(stat='identity')
     
     return(bar_num)
     
}

# Call function

bar_viz(iris, "Species", "Sepal.Length")

enter image description here

Upvotes: 0

Views: 73

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

We can use .data pronoun :

library(dplyr)

bar_viz <- function(data, grp_var, var) {

  cat_dat <- iris %>%
    group_by(.data[[grp_var]]) %>%
    summarise(mean=mean(.data[[var]])) 
  
  bar_num <- ggplot(cat_dat, aes(x= .data[[grp_var]], y=mean)) +
    geom_bar(stat='identity')
  return(bar_num)
}

# Call function

bar_viz(iris, "Species", "Sepal.Length")

enter image description here

Upvotes: 1

Related Questions