将tidyeval参数转换为字符串

时间:2020-03-11 21:06:50

标签: r stringr tidyeval r-glue

我在T中使用tidyeval在...中有一个简单的函数。可以将它们更改为字符串吗?

simple_paste <- function(...){
  my_vars <- enquos(...)
  paste(..., sep = "_x_")
}

simple_paste(hello, world)

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

1 个答案:

答案 0 :(得分:4)

将单位转换为字符,然后paste

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

或者另一种选择是eval创建表达式

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

如果我们最后需要.csv

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