David LeBauer
David LeBauer

Reputation: 31741

How to pass a list to a function in 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

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.

Upvotes: 22

Views: 23132

Answers (2)

Maiasaura
Maiasaura

Reputation: 32986

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))

Upvotes: 7

Sameer
Sameer

Reputation: 1807

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))

Upvotes: 43

Related Questions