0

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.

  • Please provide a [reproducible minimal example](https://stackoverflow.com/q/5963269/8107362). Especially, provide some sample data, e.g. with `dput()` and use the [reprex-package](https://reprex.tidyverse.org/). – mnist Sep 16 '21 at 19:52
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 18 '21 at 01:58

1 Answers1

2

We can use {{}}

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

-testing

 c_table_fn(sp)
akrun
  • 874,273
  • 37
  • 540
  • 662