'R Object not found error when using tidy evaluation and group by in function

I am writing a function that should return a pieplot. Now I don't understand why it does not find the grouping variable. Every time I run this, it throws an error: Error in as.list.environment(x, all.names = TRUE): object 't1gender' not found. t1gender is the variable I want to group by.

The thing is, I cannot just use the variable in a function as I would usually with group_by(). See here: dcl-prog.stanford.edu/tidy-eval-basics.html. I want varname to behave as a hybrid between an environment variable and a data variable. Like an environment variable, I want it to refer to another value (t1gender). Then, I want group_by() to treat that value (t1gender) as a data variable and look inside data for the matching column.

Any hints are very welcome!

Here is my reprex:

library(dplyr)
library(plotly)

data <- data.frame(
  ID_code = c(1001L,1002L,1003L,
              1004L,1005L,1006L,1007L,1008L,1009L,1010L),
  t1gender = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L)
)

pie_plot <- function(data = data, labels, varname, colors) {
  lbls <- labels
  count <- data %>%
    dplyr::group_by({{varname}}) %>% 
    tally() %>%
    .[2] %>%
    .[1:length(labels), ] %>%
    unlist(.)
  df <- as_tibble(cbind(count, lbls))
  plot_ly(df, labels = ~lbls, values = ~count,
          marker = list(colors = colors,
                        line = list(color = '#FFFFFF', width = 1)),
          type = "pie", width = 280, height = 280)
}

pie_plot(data, labels = c("Male", "Female"), varname = t1gender, colors = c('#440154FF', '#21908CFF'))
#> Error in as.list.environment(x, all.names = TRUE): object 't1gender' not found

Thanks a lot!

r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source