【问题标题】:How to create a function that attaches the input to the end of an existing string in the function?如何创建一个函数,将输入附加到函数中现有字符串的末尾?
【发布时间】:2023-01-10 02:31:40
【问题描述】:

假设我有这个功能:

f <- function(input){
  name <- "hello_"
  }

我希望能够使用

f(world)

并将name重命名为"hello_world"

重要的是我不希望输入是一个字符串。所以解决方案应该不涉及f("world")

【问题讨论】:

    标签: r string function


    【解决方案1】:

    像这样使用substitute

    f <- function(input) paste0("hello_", substitute(input))
    f(world)
    ## [1] "hello_world"
    

    请注意,以这种方式设计您的函数以使用非标准评估 (NSE) 将降低它们的编程灵活性。例如,假设我们将"world" 存储在x 中。然后我们得到以下显然不是我们想要的。

    x <- "world"
    f(x)
    ## [1] "hello_x"
    

    可以绕过它,但很痛苦:

    do.call("f", list(x))
    ## [1] "hello_world"
    

    【讨论】:

      猜你喜欢
      • 2014-03-06
      • 2012-06-28
      • 1970-01-01
      • 2017-09-29
      • 2018-02-28
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 2020-08-19
      相关资源
      最近更新 更多