【问题标题】:Is there a way make a parameter of a function be put in quotes in one life of code and not the other?有没有办法让函数的参数在代码的一个生命周期而不是另一个生命周期中放在引号中?
【发布时间】:2021-04-13 15:43:55
【问题描述】:

我没有展示我的实际代码,因为它有很多运行部分,所以让我展示一下我遇到的问题。我有这个功能:

paste <- function(d) {
        print(paste0(d,"_test", sep =""))
}

如果我做了paste(advising),我想要返回的是“advising_test”。

我不只是在做paste("advising") 的原因是因为在我正在编写的函数中,advising 需要在引号中同时使用以命名特定对象,并且需要用作数据框的名称我正在做另一个功能。因此,我需要弄清楚如何在代码中粘贴带引号的参数,以便可以双向使用该术语。

【问题讨论】:

    标签: r function object paste


    【解决方案1】:
    paste <- function(d) {
            print(paste0(ensym(d),"_test", sep =""))
    }
    

    编辑:你可以看看https://rlang.r-lib.org/reference/nse-defuse.html

    【讨论】:

      【解决方案2】:

      使用 substitute 。没有使用任何包。

      mypaste <- function(d) print(paste0(substitute(d), "_test"))
      
      # test
      mypaste(advising)
      ## [1] "advising_test"
      

      【讨论】:

        猜你喜欢
        • 2020-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        • 1970-01-01
        相关资源
        最近更新 更多