Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list to a function in R?

Tags:

function

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.

like image 765
David LeBauer Avatar asked Jun 27 '11 17:06

David LeBauer


People also ask

How do I pass a list to a function in R?

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.

Can a list be passed to a function?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

Can you pass a function to a function R?

Adding Arguments in RWe can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis.


2 Answers

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))
like image 78
Sameer Avatar answered Sep 18 '22 14:09

Sameer


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))
like image 20
Maiasaura Avatar answered Sep 18 '22 14:09

Maiasaura