【问题标题】:Modifying variable order within a nested function在嵌套函数中修改变量顺序
【发布时间】:2020-01-29 14:19:51
【问题描述】:

我想对传递给函数的变量的顺序进行变量控制。最好用下面的例子来说明;

假设我们有以下函数,其中两个变量在函数的本地命名空间中定义,并传递给该命名空间内的嵌套函数:

testfunc = function(){

  a=1
  b=2

  return(sprintf('first %s, then %s', a,b))
}

是否可以定义变量ab传递给sprintf的顺序?

大概是这样的:

我的尝试:

testfunc = function(...){

  a=1
  b=2

  return(sprintf('first %s, then %s', ...))
}

testfunc(...=b,a)

显然,由于语法问题,上述方法不起作用......

任何帮助将不胜感激。

【问题讨论】:

    标签: r


    【解决方案1】:

    类似这样的:

    test <- function(ord) {
        l <- list(
            a = "x",
            b = "y"
        )
        args <- c(l[ord], fmt = "%s %s")
        do.call(sprintf, args)
    }
    test(c(1, 2))
    #> [1] "x y"
    test(c(2, 1))
    #> [1] "y x"
    test(c(1, 1))
    #> [1] "x x"
    test(c(2, 2))
    #> [1] "y y"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多