Hi
I am looking for a way to have a function which does grouping with multiple variables and additionally one variable to have something like wt in count...
So far my solution is:
library(tidyverse)
set.seed(1234)
# base data set
df <- tibble(
g1 = c("A", "B")[round(runif(100, 1, 2))],
g2 = c("X", "Y")[round(runif(100, 1, 2))],
v = runif(100, 0, 100)
)
# my function
grpsum <- function(data, sumVar, ...) {
data %>%
group_by(...) %>%
summarise(total = sum({{sumVar}}))
}
df %>% grpsum(v, g1, g2)
#> # A tibble: 4 x 3
#> # Groups: g1 [2]
#> g1 g2 total
#> <chr> <chr> <dbl>
#> 1 A X 1176.
#> 2 A Y 1422.
#> 3 B X 1254.
#> 4 B Y 1159.
df %>% grpsum(v, g1)
#> # A tibble: 2 x 2
#> g1 total
#> <chr> <dbl>
#> 1 A 2598.
#> 2 B 2413.
df %>% grpsum(v)
#> # A tibble: 1 x 1
#> total
#> <dbl>
#> 1 5012.
To improve this function I would like to make sumVar optional. If sumVar is not preset count values, here total would be 100.
I would also prefer to have sumVar as an explicit parameter and not somewhere hidden in the ....
Alternatively, is there another way pass multiple grouping variables without using ...?
Thank you for any ideas!
(I hope I haven't missed a topic where this is already answered - if so: sorry for that!)