将 tidyeval 参数转换为字符串

Joh*_*nry 4 r stringr tidyeval r-glue

我在 R 中有一个...使用 tidyeval 的简单函数。是否可以将这些更改为字符串?

simple_paste <- function(...){
  my_vars <- enquos(...)
  paste(..., sep = "_x_")
}
Run Code Online (Sandbox Code Playgroud)

simple_paste(hello, world)

作为输出,我想得到"hello_x_world". 我也可以考虑使用glue函数 orstr_c代替paste,尽管我不确定这会更好。

akr*_*run 5

将 quosure 转换为字符,然后paste

simple_paste <- function(...) {
  purrr::map_chr(enquos(...), rlang::as_label) %>% 
          paste(collapse="_x_")
   }
simple_paste(hello, world)
#[1] "hello_x_world"
Run Code Online (Sandbox Code Playgroud)

或者另一种选择是eval使用表达式

simple_paste <- function(...)  eval(expr(paste(!!! enquos(...), sep="_x_")))[-1]
simple_paste(hello, world)
#[1] "hello_x_world"
Run Code Online (Sandbox Code Playgroud)

如果我们.csv最后需要

simple_paste <- function(...)  eval(expr(paste0(paste(!!! enquos(...), sep="_x_"), ".csv")))[-1]
simple_paste(hello, world)
#[1] "hello_x_world.csv"
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用 `as_string()` 而不是 `quo_name()` ,后者可能会被弃用。如果您确实想要常规名称行为,请使用更明确的“as_label()”。但 `as_string()` 看起来就在这里。请参阅“?as_label”。 (2认同)