Function default arguments and named values

后端 未结 2 1574
天涯浪人
天涯浪人 2020-12-23 02:10

Let\'s say I have an R function in which the arguments can be a one of a few predefined named values (one of which is the default) or a custom character vector. How should I

2条回答
  •  死守一世寂寞
    2020-12-23 02:38

    From your example we have the choice of "CORE" and "ALL". If those are the two options, then we specify them in the function definition for the argument 'members'. E.g.:

    foo <- function(x, members = c("CORE", "ALL")) {
        ## do something
    }
    

    That function definition sets up the allowed values for argument 'members', with a default of "CORE" as this is the first named option.

    The code that one uses within the function body is match.arg(), as @Joris has already mentioned, but because we have set the function up as above, we can simply the usage to just match.arg(members).

    So we can write foo as:

    foo <- function(x, members = c("CORE", "ALL")) {
        ## evaluate choices
        members <- match.arg(members)
        ## do something
        print(members)
    }
    

    Which we use like this:

    > foo()
    [1] "CORE"
    > foo(members = "CORE")
    [1] "CORE"
    > foo(members = "ALL")
    [1] "ALL"
    > foo(members = "3rdRate")
    Error in match.arg(members) : 'arg' should be one of “CORE”, “ALL”
    

    Notice the behaviour when we supply an string not included in the set of options. We get an intuitive error message, all because we set up the options in the function arguments.

提交回复
热议问题