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.
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.
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.
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.
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With