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 Furthermore, ?function doesn't work and help('function') does not provide information on passing a list to a function.
update
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.
plothas a method that handles lists. To do something similar withfoo, you would need to make it generic and write appropriate methods.plot(list(x=1,y=1))callsplot.default, which usesxy.coords. The source ofxy.coordshas an if/else branch to handle multiple types ofxarguments (ts,matrix,data.frame,formula,complex,list). So it's not a generic using methods. The analogous solution would be to definefoo(a, b=NULL)and have an if/else branch whenbis null to handle multiple classes ofa.