代码之家  ›  专栏  ›  技术社区  ›  shians

最后一个参数为空时如何处理?

r
  •  4
  • shians  · 技术社区  · 6 年前

    使用时 ... 要捕获其他参数,请将最后一个参数留空并尝试使用 list(...) 将产生错误

    f <- function(x, ...) {
        args <- list(...)
    }
    
    f(x = 0, y = 10,)
    
    
    > Error in f(x = 0, y = 10, ) : argument is missing, with no default
    

    你会得到以下结果

    f1 <- function(x, ...) {
        f2(x, ...)
    }
    
    f2 <- function(x, ...) {
        list(...)
    }
    
    f1(x = 0, y = 10,)
    
    > Error in f2(x, ...) : argument is missing, with no default
    

    现在很清楚出了什么问题。是否有惯用的技术来捕获错误并用有用的消息报告它?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Andre Elrico    6 年前
    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
    


    因此,有意义的错误处理可以如下所示:

    感谢@Roland的加入。

    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.