26

When creating a function in R, we usually specify the number of argument like

function(x,y){
}

That means it takes only two arguments. But when the numbers of arguments are not specified (For one case I have to use two arguments but another case I have to use three or more arguments) how can we handle this issue? I am pretty new to programming so example will be greatly appreciated.

2
  • instead of each variable, you could hand over one list containing all variables. The list can be any length. So x would be a list. Commented Feb 8, 2018 at 20:56
  • 1
    you are looking for ellipsis Commented Feb 8, 2018 at 21:01

2 Answers 2

45
d <- function(...){
    x <- list(...) # THIS WILL BE A LIST STORING EVERYTHING:
    sum(...)       # Example of inbuilt function
}

d(1,2,3,4,5)

[1] 15 
Sign up to request clarification or add additional context in comments.

5 Comments

Putting it in a list is probably appropriate for whatever Lzz0 wants to do, but fyi, in your example you could skip the list and unlist and just do sum(...)
Thanks, but another thought came to my mind. What will the situation if I want to use a list for sum and another list for subtraction. I mean can I give two sets of list (the number of variables of each set are not specific).
You will need to update the question with examples. Or maybe ask a different question. I really cant understand what you mean. If you need to subtract two lists you can use Map
Suppose, in your example if I put d (1,2,3,....10,11) whatever number, the last two number always give me their multiplication and others are their sums. I mean I want to return two output from one list of input.
d=function(...){x=list(...);c(sum=sum(unlist(head(x,-2))),prod=prod(unlist(tail(x,2))))} This will do the trick
22

You can use ... to specify an additional number of arguments. For example:

myfun <- function(x, ...) {
    for(i in list(...)) {
        print(x * i)
    }
}

> myfun(4, 3, 1)
[1] 12
[1] 4
> myfun(4, 9, 1, 0, 12)
[1] 36
[1] 4
[1] 0
[1] 48
> myfun(4)

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.