简体   繁体   中英

How do I quote an expression that contains a call to quote and unquote a string within it?

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM