问题描述
我一直很难找到有关如何将列表传递给R中的函数的信息.
I have been having difficulty finding information about how to pass a list to a function in R.
例如,我以前使用过这种方法
I have used this approach before, e.g.
plot(list(x=1,y=1))
但以下示例给了我一个错误:
but the following example gives me an error:
foo <- function(a, b) c <- a + b
foo(list(a=1,b=1))
Error in foo(list(a = 1, b = 1)) :
argument "b" is missing, with no default
此外,?function
不起作用, help('function')
不提供有关将列表传递给函数的信息.
Furthermore, ?function
doesn't work and help('function')
does not provide information on passing a list to a function.
更新
为澄清起见,我理解如何将列表用作单个参数,但是我感到困惑,因为我印象中函数的属性是可以将多个参数作为列表传递.看来这种印象是不正确的.相反,许多功能是专门为处理列表而编写的,如下面的评论和答案所述.
To clarify, I understand how I can use a list as a single argument, but I was confused because I was under the impression that a property of functions was that multiple arguments could be passed as a list. It appears that this impression was incorrect. Rather, many functions are written specifically to handle lists, as described in the comments and answers below.
推荐答案
使用do.call
foo <- function(a, b) a + b
do.call(foo, list(a=1,b=1))
或者,你可以做
foo <- function(l) l$a + l$b
foo(list(a=1,b=1))
这篇关于如何将列表传递给R中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!