conditional inclusion of arguments in a function call

后端 未结 2 2118
忘掉有多难
忘掉有多难 2021-02-20 10:49

I want to call a function but depending on the situation I might call it with extra arguments or not. Here is a simple example:

FUN <- function(arg1 = \"defau         


        
相关标签:
2条回答
  • 2021-02-20 11:06

    Continuing the discussion from the comments on flodel's answer, here's an extension of my idea, out of curiosity. Not sure if it's really a feasible option:

    FUN(arg1 = x1, arg2 = x2, arg3 = if(use.arg3) x3 else formals(FUN)$arg3)
    
    0 讨论(0)
  • 2021-02-20 11:08

    One solution is to use do.call after building a list with the proper arguments:

    do.call(FUN, c(list(arg1 = x1, arg2 = x2),   # unconditional args
                   list(arg3 = x3)[use.arg3]))   # conditional arg
    

    And it generalizes well to multiple conditions:

    do.call(FUN, c(list(arg1 = x1)[use.arg1]     # conditional arg
                   list(arg2 = x2)[use.arg2]     # conditional arg
                   list(arg3 = x3)[use.arg3]))   # conditional arg
    
    0 讨论(0)
提交回复
热议问题