1

I use elipsis because I want to use a varying number of variables in my function. I cannot seem to call the individual elements in a loop and use them in simple mathematical operations.

tst <- function(...) {
  print(..1)
  q = 1 + ..1
  print(q)
  for (i in 1:3) {
    val <- get(paste0("..", i))
    print(val)
    s = 1 + val  
  }
}

If I run tst(1, 3, 4) I expect to get output like

[1] 1
[1] 2
[1] 1
[1] 3
[1] 4

Instead I get

[1] 1

Error in get(paste0("..", i)) : object '..1' not found

This tells me that outside the loop, the ..1 is recognized as a numeric object, and yet inside the loop it cannot find it.

Shree
  • 10,835
  • 1
  • 14
  • 36
Helle
  • 23
  • 4
  • I apologize for the formatting. I am trying to fix it, but.... – Helle Jun 12 '19 at 00:24
  • use `for (i in c(...))` – Onyambu Jun 12 '19 at 00:48
  • 1
    I like Shane's answer for simplicity (use `args = list(...)`, then you can loop, `lapply`, `do.call`, etc.), but there's lots of info at (possible duplicate) [How to use R's ellipsis feature when writing your own function?](https://stackoverflow.com/a/3057419/903061) – Gregor Thomas Jun 12 '19 at 02:03
  • Because I am using this in mle it turns out I cannot use "...". As a result I need to be able to use a loop an call the arguments in the function, but I cannot get the call recognized as a variable. I would like the call of tst(1,2,3) to be [1] 2 and [1] 2. Instead it is [1] 2 [1] "p2" where tst <- function(p1,p2,p3) { print(p2) print(paste0("p","2"))}. Should I be posting this as a separate question? – Helle Jun 12 '19 at 21:21

1 Answers1

0

Simply set a vector to equal the arguments at the outset, then you can refer to them by an index. Everywhere you used ... I replaced with the indexing vector val[[]]:

tst <- function(...) {
  val <- c(...)
  print(val[[1]])
  q = 1 + val[[1]]
  print(q)
  for (i in 1:3) {
    print(val[[i]])
    s = 1 + val[[i]]  
  }
}

Output:

> tst(1, 3, 4)
[1] 1
[1] 2
[1] 1
[1] 3
[1] 4
Marian Minar
  • 1,344
  • 10
  • 25