【问题标题】:How to specify a number of arguments to a function from a vector?如何从向量中为函数指定多个参数?
【发布时间】:2014-04-19 03:42:23
【问题描述】:

假设f 是一个可以接受不同数量参数的函数。我有一个向量x,其条目用作f 的参数。

x=c(1,2,3) 
f(x[], otherarguments=100)

x 的条目作为参数传递给f 的正确且简单的方法是什么?谢谢!

例如

我要转换

t1 = traceplot(output.combined[1])
t2 = traceplot(output.combined[2])
t3 = traceplot(output.combined[3])
t4 = traceplot(output.combined[4])
grid.arrange(t1,t2,t3,t4,nrow = 2,ncol=2)

类似

tt=c()
for (i in 1:4){
tt[i] = traceplot(output.combined[i])
}
grid.arrange(tt[],nrow = 2,ncol=2)

【问题讨论】:

  • 请提供一个可重现的例子
  • 我猜你在找?do.call?类似do.call("f", c(as.list(x), otherarguments=100))
  • @alexis_laz 你应该把你的评论变成一个答案:) 比我的更好。
  • @agstudy 将我的评论嵌入到您的答案中可能会更好(也许,多一点“酱汁”),这样它就可以更完整地参考这个问题。当然,随意合并它!

标签: r


【解决方案1】:

这里有一个选项:

我假设你有这个函数,并且你想“矢量化”x,y,z 参数:

ss <- 
function(x,y,z,t=1)
{
  x+y+z*t
}

您可以将其包装在一个函数中,将向量作为 (x,y,z) 的参数,将“...”作为其他 ss 参数:

ss_vector <- 
  function(vec,...){
    ss(vec[1],vec[2],vec[3],...)
  }

现在你可以这样称呼它:

 ss_vector(1:3,t=2)
 [1] 9

相当于:

 ss(1,2,3,t=2)
 [1] 9

【讨论】:

    【解决方案2】:

    正如上面的@agstudy 所说,您实际上正在寻找的是对函数f() 进行向量化,而不是尝试将向量传递给非向量化函数。 R 中的所有向量化函数的形式为

    vectorized_f <- function(X) {
        x1 <- X[1]
        x2 <- X[2]
        x3 <- X[3]
        # ...
        xn <- X[length(X)]
        # Do stuff
    }
    

    作为一个例子,让我们做f &lt;- function(x1, x2, x3) x1 + x2 + x3。此函数未向量化,因此尝试传递向量需要变通方法。您可以编写f(),而不是提供三个参数,如下所示:

    vectorized_f <- function(X) {
        x1 <- X[1]
        x2 <- X[2]
        x3 <- X[3]
        x1 + x2 + x3
    }
    

    当然,您也可以尝试使其保持非矢量化,但正如我所说,这需要解决方法。例如,可以这样做:

    f <- function(x1, x2, x3) x1 + x2 + x3
    X <- c(1, 2, 3)
    funcall_string <- paste("f(", paste(X, collapse = ","), ")", collapse = "")
    # this looks like this: "f( 1,2,3 )"
    eval(parse(text = funcall_string))
    # [1] 6
    

    但这实际上比矢量化版本慢得多。

    system.time(for(i in 1:10000) {
        funcall_string <- paste("f(", paste(X, collapse = ","), ")", collapse = "")
        eval(parse(text = funcall_string))
    })
       User      System verstrichen 
       2.80        0.01        2.85
    

    对比

    system.time(for(i in 1:10000) vectorized_f(X))
       User      System verstrichen 
       0.05        0.00        0.05
    

    第, D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2022-01-17
      • 2012-05-11
      相关资源
      最近更新 更多