0

This has been possibly asked before but I have not found any relevant questions/answers (yet?).

Coming from Python (*args and **kwargs), I am trying to understand the ... construct as a function parameter in R.

Suppose, we have

test <- function(x, ...) {
  print(...)
}

test(x=c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12))

Why does it only yield

[1] 4 5 6

And how to iterate over multiple arguments (if any) ?

Jan
  • 42,290
  • 8
  • 54
  • 79
  • 1
    Study `help("print")`. Its first argument is the value to be printed. You are basically doing this `print.default(x = c(4.12345678,5,6), digits= c(7,8,9), quote = c(10,11,12))` and `print.default` is silently using the first value of the vectors (e.g., `digits= 7`) for the other arguments. – Roland Apr 13 '18 at 07:24
  • @Roland: Thanks for the explanation. – Jan Apr 13 '18 at 07:25

1 Answers1

1
test <- function(x, ...) {
  # these are equivalent and print prints only its first argument, see ?print
  print(c(4,5,6), c(7,8,9), c(10,11,12))
  print(...)

  # here's how you can get the dots
  a <- eval(substitute(alist(...))) # unevaluated dots
  # or
  a <- list(...) # evaluated dots (works fine as well  in this case)
  a
}

test(x=c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12))
# [1] 4 5 6
# [1] 4 5 6
# [[1]]
# c(4, 5, 6)
# 
# [[2]]
# c(7, 8, 9)
# 
# [[3]]
# c(10, 11, 12)
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
  • Why should I use `eval(substitute(list(...)))` instead of just `list(...)` ? Is there any advantage over the latter? – Jan Apr 13 '18 at 07:24
  • actually for this case it doesn't change anything, but what I proposed keep the dots unevaluated, try to put this in the body of the function: `print(str(eval(substitute(alist(...))))); print(str(list(...)))` – moodymudskipper Apr 13 '18 at 07:29
  • So If you try `test(x, a,b,c)` without defining the parameters you'll see `list(...)` will fail while `eval(substitute(alist(...))` won't. – moodymudskipper Apr 13 '18 at 07:37