Can ellipsis be iterated in R like *args in Python?

Viewed 245

The newly-defined function to sum inputs:

mysum=function(...){
return(sum(...))
invisible(...)
}

> mysum(1,2,3,4)
[1] 10

What if I don't use the sum function?I mean this:

mysum=function(...){
s=0
for(i in ...){
s=s+i
}
return(s)
}

It doesn't work. Can ... be iterated?

In Python,it's simple:

def mysum(*args):
    s=0
    for i in args:
        s+=i
    return(s)
2 Answers

use c() on ellipsis before the loop, and assign it inside the function:

mysum=function(...){
  vec = c(...)
  s=0
  for(i in vec){
    s=s+i
  }
  return(s)
}

mysum(1,2,3)
[1] 6

Yes!

The usual route is to stuff it into a list and then iterate over the list:

my_fun <- function(...) {
  args <- list(...)
  # do stuff with ellipses args.
}

Whether you use lapply, go straight for named arguments or just loop over (for (i in seq_along(args)) {args[[i]]}) is up to you.

If you assume ... only contains vectors, you could do:

args <- unlist(list(...))
sum(args)
Related