22

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.

4
  • You are passing a single argument to your function which expects 2. The correct call would be: foo(a=list(1), b=list(2)). If you wanted to pass to your function a single list then you have to declare it as function(a) and then call it the same way you did. Your function logic is also off since you can't add non-numeric arguments in such a way and you will have to index your lists within your function body to achieve what you want (guessing here) i.e. a[[1]] + b[[1]]. Commented Jun 27, 2011 at 17:59
  • 1
    I haven't looked into it, but I would guess that plot has a method that handles lists. To do something similar with foo, you would need to make it generic and write appropriate methods. Commented Jun 27, 2011 at 18:00
  • @Joshua, thank you for the clarification. I was under the impression that a list could be passed without special handling. Commented Jun 27, 2011 at 18:06
  • plot(list(x=1,y=1)) calls plot.default, which uses xy.coords. The source of xy.coords has an if/else branch to handle multiple types of x arguments (ts, matrix, data.frame, formula, complex, list). So it's not a generic using methods. The analogous solution would be to define foo(a, b=NULL) and have an if/else branch when b is null to handle multiple classes of a. Commented Jun 27, 2011 at 18:14

2 Answers 2

43

Use do.call

foo <- function(a, b)  a + b

do.call(foo, list(a=1,b=1))

Alternatively you can do

foo <- function(l) l$a + l$b

foo(list(a=1,b=1))
Sign up to request clarification or add additional context in comments.

Comments

7

Your function has two arguments but you are only passing one, hence the error.

You can modify your code like so:

foo <- function(a) c <- a[[1]] + a[[2]]
foo(list(a=1,b=1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.