将几个参数传递给lapply(和其他* apply)的FUN [英] passing several arguments to FUN of lapply (and others *apply)

查看:71
本文介绍了将几个参数传递给lapply(和其他* apply)的FUN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R中使用lapply时,我有一个关于将多个参数传递给函数的问题.

I have a question regarding passing multiple arguments to a function, when using lapply in R.

当我对lapply(input, myfun);的语法使用lapply时-这很容易理解,我可以这样定义myfun:

When I use lapply with the syntax of lapply(input, myfun); - this is easily understandable, and I can define myfun like that:

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

lapply(input, myfun);

input的元素作为x参数传递给myfun.

and elements of input are passed as x argument to myfun.

但是,如果我需要将更多参数传递给myfunc怎么办?例如,它的定义如下:

But what if I need to pass some more arguments to myfunc? For example, it is defined like that:

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

如何通过传递input元素(作为x参数)和其他一些参数来使用此函数?

How can I use this function with passing both input elements (as x argument) and some other argument?

推荐答案

如果您查找帮助页面,则lapply的参数之一就是神秘的....当我们查看帮助页面的参数"部分时,会发现以下行:

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

因此,您要做的就是在lapply调用中将另一个参数作为参数包含进来,如下所示:

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

lapply认识到arg1不是它知道如何处理的参数,会自动将其传递给myfun.所有其他apply函数都可以执行相同的操作.

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

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

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

这篇关于将几个参数传递给lapply(和其他* apply)的FUN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆