shians
shians

Reputation: 965

How to handle ... when final argument is empty?

When using ... to capture additional arguments, leaving the last argument empty and attempting to use list(...) will produce an error

f <- function(x, ...) {
    args <- list(...)
}

f(x = 0, y = 10,)


> Error in f(x = 0, y = 10, ) : argument is missing, with no default

Here the error message is still informative, but if you pass on the ... you end up with the following

f1 <- function(x, ...) {
    f2(x, ...)
}

f2 <- function(x, ...) {
    list(...)
}

f1(x = 0, y = 10,)

> Error in f2(x, ...) : argument is missing, with no default

Now it's very it becomes quite unclear what has gone wrong. Are there idiomatic techniques to capture the error and report it with an useful message?

Upvotes: 4

Views: 116

Answers (1)

Andre Elrico
Andre Elrico

Reputation: 11490

f <- function(x, ...) {
    return(
        as.list(substitute(list(...)))[-1]
    )
}

err <- f(x = 0, y = 10,)   #have a closer look --> str(err)

#$`y`
#[1] 10
# 
#[[2]]

fine<- f(x = 0, y = 10)

#$`y`
#[1] 10

You see in the Error case you have an empty symbol list element. I believe you can use this information as a hook for your error handling.


So your meaningful error handling can look like this:

Thanks to @Roland for joining in.

f <- function(x, ...) {
    res <- as.list(substitute(list(...)))[-1]
    if( any(  sapply(res, function(x) { is.symbol(x) && deparse(x) == "" })  ) )  stop('Please remove the the last/tailing comma "," from your input arguments.')
    print("code can run. Hurraa")
}

a <- 0; 
f(x = 0, y = a, hehe = "", "")
#[1] "code can run. Hurraa"

f(x = 0, y = a, hehe = "", "", NULL)
#[1] "code can run. Hurraa"

f(x = 0, y = a, hehe = "", "",)
#Error in f(x = 0, y = a, hehe = "", "", ) : 
#Please remove the the last/tailing comma "," from your input arguments.

f(x = 0, y = a, hehe = "", "", NULL,)
#Error in f(x = 0, y = a, hehe = "", "", NULL, ) : 
#Please remove the the last/tailing comma "," from your input arguments.

Upvotes: 3

Related Questions