[英]passing several arguments to FUN of lapply (and others *apply)
我有一个关于在R
使用lapply
时将多个参数传递给函数的问题。
当我将 lapply 与lapply(input, myfun);
的语法一起使用时lapply(input, myfun);
- 这很容易理解,我可以这样定义 myfun:
myfun <- function(x) {
# doing something here with x
}
lapply(input, myfun);
和input
元素作为x
参数传递给myfun
。
但是如果我需要向myfunc
传递更多参数怎么办? 例如,它是这样定义的:
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
如何使用此函数传递input
元素(作为x
参数)和其他一些参数?
如果您查看帮助页面, lapply
的论据lapply
是神秘的...
。 当我们查看帮助页面的 Arguments 部分时,我们发现以下行:
...: optional arguments to ‘FUN’.
所以你所要做的就是在lapply
调用中包含你的另一个参数作为参数,如下所示:
lapply(input, myfun, arg1=6)
和lapply
,认识到arg1
不是它知道如何处理的参数,将自动将其传递给myfun
。 所有其他apply
函数都可以做同样的事情。
附录:您也可以在编写自己的函数时使用...
例如,假设您编写了一个在某个时刻调用plot
的函数,并且您希望能够从函数调用中更改绘图参数。 您可以将每个参数作为参数包含在函数中,但这很烦人。 相反,您可以使用...
(作为您的函数和在其中调用 plot 的参数),并将您的函数无法识别的任何参数自动传递给plot
。
正如 Alan 所建议的,函数 'mapply' 将一个函数应用于多个多个列表或向量参数:
mapply(myfun, arg1, arg2)
参见手册页: 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)
你会得到答案:
[[1]] [1] 200
[[2]] [1] 400
[[3]] [1] 600
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
x
是一个向量或列表,并且myfun
在lapply(x, myfun)
被调用的每个元素x
分别。
选项1
如果你想使用整个arg1
在每个myfun
呼叫( myfun(x[1], arg1)
myfun(x[2], arg1)
等),使用lapply(x, myfun, arg1)
如所述的上述)。
选项 2
但是,如果您想将myfun
与x
元素一起分别调用arg1
每个元素( myfun(x[1], arg1[1])
, myfun(x[2], arg1[2])
等),它是无法使用lapply
。 相反,使用mapply(myfun, x, arg1)
(如上所述)或apply
:
apply(cbind(x,arg1), 1, myfun)
要么
apply(rbind(x,arg1), 2, myfun).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.