Hello,
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
Created on 2022-10-03 by the reprex package (v2.0.1)
I think this should do what you want!
Kind regards