Reputation: 5956
I want to create a function for use within dplyr::summarize that can retrieve the current group var as a string, then creates an expression to use that group var string to get the current value of the group.
I have the working example just called directly from summarize, but have failed to get a function to work. I am struggling to figure out what is wrong with it, but I'm wondering if it has something to do with the order of parsing for the expression? However, I am quite new to this, so would appreciate any help possible.
library(rlang)
library(dplyr)
get_group <- function(df) {
group <- group_vars(df)
exp <- paste0("unique(!!sym('", group, "'))")
parse_expr(exp)
}
df <- tibble(
x = c("a", "b", "c", "a", "b"),
y = c(1, 2, 3, 4, 2)
)
df %>% group_by(x) %>%
summarize(z = unique(!!sym(group_vars(.))))
#> # A tibble: 3 x 2
#> x z
#> <chr> <chr>
#> 1 a a
#> 2 b b
#> 3 c c
df %>% group_by(x) %>%
summarize(z = !!get_group(.))
#> Error in !sym("x"): invalid argument type
Upvotes: 2
Views: 346
Reputation: 206167
If you are using rlang
, you should try to avoid parsing strings into expressions. Consider this alternative where get_group
returns a proper quosure with the symbols already expanded
get_group <- function(df) {
group <- group_vars(df)
quo(unique(!!sym(group)))
}
df %>% group_by(x) %>%
summarize(z = !!get_group(.))
# # A tibble: 3 x 2
# x z
# <chr> <chr>
# 1 a a
# 2 b b
# 3 c c
Upvotes: 4