Reputation: 712
I have an r function in a package that I am developing, of the following format which downloads and returns a dataframe based on the argument arg1. arg1 can only be either of the options "datatype1" or "datatype2". Currently the function returns a NULL when any other value is put in for arg1. What is the best way to inform the user that it is an invalid argument and handle the else block?
output_data <- function(arg1 = "datatype1"){
if(arg1 == "datatype1){
return(dt1)
} else if (arg1 == "datatype2"){
return(dt2)
} else {
}
}
Upvotes: 0
Views: 136
Reputation: 546053
“Best” is debatable but in most situations the best course of action is indeed to fail fast. Therefore a good option is to throw an error via stop
or its relative, stopifnot
:
output_data <- function(arg1 = "datatype1"){
stopifnot(arg1 %in% paste0("datatype", 1 : 2))
if (arg1 == "datatype1") {
dt1
} else if (arg1 == "datatype2") {
dt2
}
}
(Note that I’ve removed the extraneous return
function calls from your code.)
That said, this attempt contains a lot of redundant code that gets more as you have more datasets. Why not use list lookup:
datasets = list(datatype1 = dt1, datatype2 = dt2)
output_data = function (which) {
stopifnot(which %in% names(datasets))
datasets[[which]]
}
Upvotes: 1