you can do this for sure. I included a filter_var argument, so that you can see the use of {{ for single variable isnertion. Dynamic dots are used for multiple injections.
library(dplyr)
Data <- data.frame(animal = sample(c('cat','dog','horse'),1000,TRUE,c(.6,.2,.2)),
color = sample(c('black','brown','white'),1000,TRUE),
location = sample(c('east','north','west'),1000,TRUE))
filter_group_count <- function(df,filter_var,filter_cond,...){
df |>
filter( {{filter_var}} == filter_cond) |>
group_by( ... ) |>
summarise(
count = n()
)
}
filter_group_count(df = Data, filter_var = animal, filter_cond = 'cat', color)
#> # A tibble: 3 × 2
#> color count
#> <chr> <int>
#> 1 black 197
#> 2 brown 174
#> 3 white 183
filter_group_count(df = Data, filter_var = animal, filter_cond = 'cat', color, location)
#> `summarise()` has grouped output by 'color'. You can override using the
#> `.groups` argument.
#> # A tibble: 9 × 3
#> # Groups: color [3]
#> color location count
#> <chr> <chr> <int>
#> 1 black east 62
#> 2 black north 61
#> 3 black west 74
#> 4 brown east 55
#> 5 brown north 56
#> 6 brown west 63
#> 7 white east 55
#> 8 white north 61
#> 9 white west 67
I don't really understand your second question. You can pass color as argument to ... and it will group by color only. Or what exactly do you want the function to do / what are you expecting the function to do (which is doesn't do?)?
You could type dput(head(Data,50)) (where Data is the name of your data.frame) and paste it into the forum. Maybe I can reproduce your error and see where the problem is, since atm I don't know what could cause the error.