issues with dplyr group_by within a custom function; related to tidyeval?

I'm trying to write a function to make a long three way contingency table use group_by and summarize from dplyr. I start with a tibble containing 3 factor variables: year, mammogram and sp.

> c_table_fn <- function(x){
+ factors %>%
+ group_by(year,mammogram,x) %>%
+ summarize(n = n())}
> c_table_fn(sp)

Error: Must group by variables found in `.data`.
* Column `x` is not found

My function gives me the above error. However, when I run the same code not in a function, it runs fine and I get the desired table.

> factors %>%
+ group_by(year,mammogram,sp) %>%
+ summarize(n = n())
`summarise()` has grouped output by 'year', 'mammogram'. You can override using the `.groups` argument.

I think this is due to an issue with tidy evaluation. I tried changing x in my function to {{x}} as well as .data[[x]] as suggested in the dplyr programming vignette, but this did not help.

Submitted September 16th 2021 by Admin


We can use {{}}

c_table_fn <- function(x){ factors %>% group_by(year,mammogram,{{x}}) %>% summarize(n = n())



Admin | 1 month ago

Relevant Questions