将几个参数传递给lapply的乐趣(以及其他*适用)

Vas*_*y A 83 r lapply

(这一定是一个非常基本的问题,但到目前为止我没有在R手册中找到答案......)

当我使用lapply语法时lapply- 这很容易理解,我可以像这样定义myfun:

myfun <- function(x) {
 # doing something here with x
}

lapply(input, myfun);
Run Code Online (Sandbox Code Playgroud)

和元素R作为lapply(input, myfun);参数传递给input.

但是,如果我需要传递更多参数x呢?例如,它定义如下:

myfun <- function(x, arg1) {
 # doing something here with x and arg1
}
Run Code Online (Sandbox Code Playgroud)

如何使用此函数传递两个myfun元素(作为myfunc参数)和其他一些参数?

Jon*_*sen 102

如果你查看帮助页面,其中一个参数lapply是神秘的....当我们查看帮助页面的Arguments部分时,我们会找到以下行:

...: optional arguments to ‘FUN’.
Run Code Online (Sandbox Code Playgroud)

所以你要做的就是在lapply调用中包含你的另一个参数作为参数,如下所示:

lapply(input, myfun, arg1=6)
Run Code Online (Sandbox Code Playgroud)

并且lapply,认识到这arg1不是一个它知道如何处理的参数,将自动传递给它myfun.所有其他apply功能都可以做同样的事情.

附录:您也可以...在编写自己的函数时使用.例如,假设您编写了一个plot在某个时刻调用的函数,并且您希望能够从函数调用中更改绘图参数.您可以在函数中包含每个参数作为参数,但这很烦人.相反,你可以使用...(作为你的函数和在其中绘图的调用的参数),并且让你的函数无法识别的任何参数被自动传递给plot.

  • 我刚刚在另一篇文章中找到了答案:mapply(myfun,df $ input,df $ input2) (9认同)

And*_*rew 17

正如Alan所建议的,函数'mapply'将函数应用于多个Multiple Lists或Vector Arguments:

mapply(myfun, arg1, arg2)
Run Code Online (Sandbox Code Playgroud)

请参见手册页:https: //stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html


Gpw*_*ner 8

您可以通过以下方式执行此操作:

 myfxn <- function(var1,var2,var3){
      var1*var2*var3

    }

    lapply(1:3,myfxn,var2=2,var3=100)
Run Code Online (Sandbox Code Playgroud)

你会得到答案:

[[1]] [1] 200

[[2]] [1] 400

[[3]] [1] 600

  • 谢谢,但上面已经给出了这个答案 (4认同)

han*_*frc 6

myfun <- function(x, arg1) {
 # doing something here with x and arg1
}
Run Code Online (Sandbox Code Playgroud)

x是一个向量或一个列表,并为每个元素分别调用myfunin 。lapply(x, myfun)x

选项1

如果您想使用全arg1在每个myfun呼叫(myfun(x[1], arg1)myfun(x[2], arg1)等),使用lapply(x, myfun, arg1)(如上所述)。

选项 2

如果您想然而就像打电话myfun到的每一个元素arg1单独一起的元素xmyfun(x[1], arg1[1])myfun(x[2], arg1[2])等),这是不可能的使用lapply。相反,使用mapply(myfun, x, arg1)(如上所述)或apply

 apply(cbind(x,arg1), 1, myfun)
Run Code Online (Sandbox Code Playgroud)

或者

 apply(rbind(x,arg1), 2, myfun).
Run Code Online (Sandbox Code Playgroud)