Search code examples
rellipsis

why does assigning to the ellipsis `... <- 1` not throw an error?


NB: What I do below may not be directly useful. But I would like to understand why R works this way.


The ellipsis (...) has a special meaning in R functions. Evaluating it directly will throw an error.

> ...
Error: '...' used in an incorrect context
> foo <- \(...) return(...)
> b <- foo(a=1)
Error: '...' used in an incorrect context

Interestingly, assigning to it throws no error.

> ... <- 1

For other reserved words like NULL or NA, an error is thrown

NULL <- 1
Error in NULL <- 1 : invalid (do_set) left side assignment

To the R experts: What exactly is happening here? Is there a reason, why the assignment does not throw an error? Is it useful in some way?


Solution

  • It isn't a reserved word, it's just a name that is interpreted in a special way. Reserved words are treated specially by the parser. Only the code evaluator treats ... specially, it has no syntax implications.

    As far as I know, the only way to retrieve a value you assigned to a variable named ... is to use get(), or similar:

    ... <- 1
    ...             # gives an error
    get("...")      # this is fine
    globalenv()$... # so is this
    

    Edited to add:

    Regarding the difference between

    f <- function(...) return(...)
    f(1)
    

    (which throws an error) and

    g <- function(...) return(c(...))
    g(1)
    

    which is fine:

    return() is a primitive function. They do pretty much what they like with arguments. What return(arg) does is to evaluate arg in the context where return() is being called, i.e. the function evaluation frame. Since arg in the f() example is just ..., it's like trying to evaluate ... on its own, and that's not allowed.

    You can see the source for the C code implementing return() here: https://github.com/wch/r-source/blob/a87aee1d3a7bec255650bb3aafdd8bd4974bec2f/src/main/eval.c#L3011-L3025 if you want to see the gory details.