【问题标题】:Converting tidyeval arguments to string将 tidyeval 参数转换为字符串
【发布时间】:2020-06-23 22:24:37
【问题描述】:

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

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

simple_paste(hello, world)

作为输出,我想得到"hello_x_world"。我也可以考虑使用glue 函数或str_c 而不是paste,虽然我不确定这会更好。

【问题讨论】:

    标签: r stringr tidyeval r-glue


    【解决方案1】:

    将quosure转换为字符,然后paste

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

    或者另一种选择是evaluate 一个表达式

    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"
    

    【讨论】:

    • 谢谢!更进一步,您对以.csv 结束字符串有什么建议吗? -- hello_x_world.csv
    • 我建议使用as_string() 而不是quo_name(),这可能会被弃用。如果您真的想要 quo-name 行为,请使用更明确的 as_label()。但是as_string() 看起来就在这里。见?as_label
    猜你喜欢
    • 2020-01-15
    • 2011-12-13
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多