(这一定是一个非常基本的问题,但到目前为止我没有在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
.
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
您可以通过以下方式执行此操作:
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
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
Run Code Online (Sandbox Code Playgroud)
x
是一个向量或一个列表,并为每个元素分别调用myfun
in 。lapply(x, myfun)
x
选项1
如果您想使用全arg1
在每个myfun
呼叫(myfun(x[1], arg1)
,myfun(x[2], arg1)
等),使用lapply(x, myfun, arg1)
(如上所述)。
选项 2
如果您想然而就像打电话myfun
到的每一个元素arg1
单独一起的元素x
(myfun(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)